aboutsummaryrefslogtreecommitdiff
path: root/tools/mhmake/src
diff options
context:
space:
mode:
Diffstat (limited to 'tools/mhmake/src')
-rw-r--r--tools/mhmake/src/Makefile.am62
-rw-r--r--tools/mhmake/src/bisondata/bison.m4556
-rw-r--r--tools/mhmake/src/bisondata/c++.m4170
-rw-r--r--tools/mhmake/src/bisondata/c-skel.m425
-rw-r--r--tools/mhmake/src/bisondata/c.m4477
-rw-r--r--tools/mhmake/src/bisondata/lalr1.cc1174
-rw-r--r--tools/mhmake/src/bisondata/location.cc279
-rw-r--r--tools/mhmake/src/bisondata/m4sugar/foreach.m4400
-rw-r--r--tools/mhmake/src/bisondata/m4sugar/m4sugar.m42789
-rw-r--r--tools/mhmake/src/bisondata/yacc.c1741
-rw-r--r--tools/mhmake/src/build.cpp1683
-rw-r--r--tools/mhmake/src/commandqueue.cpp410
-rw-r--r--tools/mhmake/src/commandqueue.h73
-rw-r--r--tools/mhmake/src/curdir.cpp38
-rw-r--r--tools/mhmake/src/curdir.h47
-rw-r--r--tools/mhmake/src/fileinfo.cpp369
-rw-r--r--tools/mhmake/src/fileinfo.h442
-rw-r--r--tools/mhmake/src/flex.skl3425
-rw-r--r--tools/mhmake/src/flexint.h63
-rw-r--r--tools/mhmake/src/flexlexer.h271
-rw-r--r--tools/mhmake/src/functions.cpp983
-rw-r--r--tools/mhmake/src/md5.cpp455
-rw-r--r--tools/mhmake/src/md5.h58
-rw-r--r--tools/mhmake/src/mhmake.cpp158
-rw-r--r--tools/mhmake/src/mhmakefileparser.cpp1451
-rw-r--r--tools/mhmake/src/mhmakefileparser.h431
-rw-r--r--tools/mhmake/src/mhmakelexer.l922
-rw-r--r--tools/mhmake/src/mhmakeparser.y284
-rw-r--r--tools/mhmake/src/refptr.h124
-rw-r--r--tools/mhmake/src/rule.cpp301
-rw-r--r--tools/mhmake/src/rule.h110
-rw-r--r--tools/mhmake/src/stdafx.cpp24
-rw-r--r--tools/mhmake/src/stdafx.h92
-rw-r--r--tools/mhmake/src/util.cpp812
-rw-r--r--tools/mhmake/src/util.h279
35 files changed, 20978 insertions, 0 deletions
diff --git a/tools/mhmake/src/Makefile.am b/tools/mhmake/src/Makefile.am
new file mode 100644
index 000000000..0478f1645
--- /dev/null
+++ b/tools/mhmake/src/Makefile.am
@@ -0,0 +1,62 @@
+SRCS = mhmakeparser.y mhmakelexer.l mhmake.cpp mhmakefileparser.cpp util.cpp \
+ functions.cpp fileinfo.cpp rule.cpp md5.c build.cpp curdir.cpp \
+ commandqueue.cpp
+
+if DEBUG
+bin_PROGRAMS=mhmake_dbg
+mhmake_dbg_SOURCES = $(SRCS)
+else
+bin_PROGRAMS=mhmake
+mhmake_SOURCES = $(SRCS)
+endif
+
+LEX=flex++
+AM_LFLAGS=-8
+
+YACC=bison++
+AM_YFLAGS=-d
+
+mhmakelexer.o: mhmakelexer.cpp mhmakelexer.h
+mhmakelexer.cpp: mhmakelexer.l
+mhmakelexer.h: mhmakelexer.l
+
+mhmakeparser.o: mhmakeparser.cpp mhmakeparser.h
+mhmakeparser.cpp: mhmakeparser.y
+mhmakeparser.h: mhmakeparser.y
+
+.l.cpp:
+ $(LEXCOMPILE) -S$(srcdir)/flexskel.cc -H$(srcdir)/flexskel.h -h$(@:%.cpp=%.h) -otemp1234.456 $<
+ echo '#include "stdafx.h"' > $@
+ cat temp1234.456 >> $@
+ rm temp1234.456
+
+.y.cpp:
+ $(YACCCOMPILE) -S$(srcdir)/bison.cc -H$(srcdir)/bison.h -h$(@:%.cpp=%.h) -otemp1234.456 $<
+ echo '#include "stdafx.h"' > $@
+ cat temp1234.456 >> $@
+ rm temp1234.456
+
+
+.l.h:
+ $(LEXCOMPILE) -S$(srcdir)/flexskel.cc -H$(srcdir)/flexskel.h -h$@ -otemp1234.456 $<
+ echo '#include "stdafx.h"' > $(@:%.h=%.cpp)
+ cat temp1234.456 >> $(@:%.h=%.cpp)
+ rm temp1234.456
+
+.y.h:
+ $(YACCCOMPILE) -S$(srcdir)/bison.cc -H$(srcdir)/bison.h -h$@ -otemp1234.456 $<
+ echo '#include "stdafx.h"' > $(@:%.h=%.cpp)
+ cat temp1234.456 >> $(@:%.h=%.cpp)
+ rm temp1234.456
+
+# set the include path found by configure
+INCLUDES= $(all_includes)
+
+LDADD = /usr/lib/libpopt.a
+
+# the library search path.
+if DEBUG
+mhmake_dbg_LDFLAGS = $(all_libraries)
+else
+mhmake_LDFLAGS = $(all_libraries)
+endif
diff --git a/tools/mhmake/src/bisondata/bison.m4 b/tools/mhmake/src/bisondata/bison.m4
new file mode 100644
index 000000000..af7c8f7a7
--- /dev/null
+++ b/tools/mhmake/src/bisondata/bison.m4
@@ -0,0 +1,556 @@
+ -*- Autoconf -*-
+
+# Language-independent M4 Macros for Bison.
+# Copyright (C) 2002, 2004, 2005, 2006, 2007, 2008 Free Software Foundation,
+# Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+## ---------------- ##
+## Identification. ##
+## ---------------- ##
+
+# b4_copyright(TITLE, YEARS)
+# --------------------------
+m4_define([b4_copyright],
+[b4_comment([A Bison parser, made by GNU Bison b4_version.])
+
+b4_comment([$1
+
+m4_text_wrap([Copyright (C) $2 Free Software Foundation, Inc.], [ ])
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.])
+
+b4_comment([As a special exception, you may create a larger work that contains
+part or all of the Bison parser skeleton and distribute that work
+under terms of your choice, so long as that work isn't itself a
+parser generator using the skeleton or a modified version thereof
+as a parser skeleton. Alternatively, if you modify or redistribute
+the parser skeleton itself, you may (at your option) remove this
+special exception, which will cause the skeleton and the resulting
+Bison output files to be licensed under the GNU General Public
+License without this special exception.
+
+This special exception was added by the Free Software Foundation in
+version 2.2 of Bison.])])
+
+
+## ---------------- ##
+## Error handling. ##
+## ---------------- ##
+
+# The following error handling macros print error directives that should not
+# become arguments of other macro invocations since they would likely then be
+# mangled. Thus, they print to stdout directly.
+
+# b4_cat(TEXT)
+# ------------
+# Write TEXT to stdout. Precede the final newline with an @ so that it's
+# escaped. For example:
+#
+# b4_cat([[@complain(invalid input@)]])
+m4_define([b4_cat],
+[m4_syscmd([cat <<'_m4eof'
+]m4_bpatsubst(m4_dquote($1), [_m4eof], [_m4@`eof])[@
+_m4eof
+])dnl
+m4_if(m4_sysval, [0], [], [m4_fatal([$0: cannot write to stdout])])])
+
+# b4_error(KIND, FORMAT, [ARG1], [ARG2], ...)
+# -------------------------------------------
+# Write @KIND(FORMAT@,ARG1@,ARG2@,...@) to stdout.
+#
+# For example:
+#
+# b4_error([[warn]], [[invalid value for `%s': %s]], [[foo]], [[3]])
+m4_define([b4_error],
+[b4_cat([[@]$1[(]$2[]]dnl
+[m4_if([$#], [2], [],
+ [m4_foreach([b4_arg],
+ m4_dquote(m4_shift(m4_shift($@))),
+ [[@,]b4_arg])])[@)]])])
+
+# b4_error_at(KIND, START, END, FORMAT, [ARG1], [ARG2], ...)
+# ----------------------------------------------------------
+# Write @KIND_at(START@,END@,FORMAT@,ARG1@,ARG2@,...@) to stdout.
+#
+# For example:
+#
+# b4_error_at([[complain]], [[input.y:2.3]], [[input.y:5.4]],
+# [[invalid %s]], [[foo]])
+m4_define([b4_error_at],
+[b4_cat([[@]$1[_at(]$2[@,]$3[@,]$4[]]dnl
+[m4_if([$#], [4], [],
+ [m4_foreach([b4_arg],
+ m4_dquote(m4_shift(m4_shift(m4_shift(m4_shift($@))))),
+ [[@,]b4_arg])])[@)]])])
+
+# b4_warn(FORMAT, [ARG1], [ARG2], ...)
+# ------------------------------------
+# Write @warn(FORMAT@,ARG1@,ARG2@,...@) to stdout.
+#
+# For example:
+#
+# b4_warn([[invalid value for `%s': %s]], [[foo]], [[3]])
+#
+# As a simple test suite, this:
+#
+# m4_divert(-1)
+# m4_define([asdf], [ASDF])
+# m4_define([fsa], [FSA])
+# m4_define([fdsa], [FDSA])
+# b4_warn([[[asdf), asdf]]], [[[fsa), fsa]]], [[[fdsa), fdsa]]])
+# b4_warn([[asdf), asdf]], [[fsa), fsa]], [[fdsa), fdsa]])
+# b4_warn()
+# b4_warn(1)
+# b4_warn(1, 2)
+#
+# Should produce this without newlines:
+#
+# @warn([asdf), asdf]@,[fsa), fsa]@,[fdsa), fdsa]@)
+# @warn(asdf), asdf@,fsa), fsa@,fdsa), fdsa@)
+# @warn(@)
+# @warn(1@)
+# @warn(1@,2@)
+m4_define([b4_warn],
+[b4_error([[warn]], $@)])
+
+# b4_warn_at(START, END, FORMAT, [ARG1], [ARG2], ...)
+# ---------------------------------------------------
+# Write @warn(START@,END@,FORMAT@,ARG1@,ARG2@,...@) to stdout.
+#
+# For example:
+#
+# b4_warn_at([[input.y:2.3]], [[input.y:5.4]], [[invalid %s]], [[foo]])
+m4_define([b4_warn_at],
+[b4_error_at([[warn]], $@)])
+
+# b4_complain(FORMAT, [ARG1], [ARG2], ...)
+# ----------------------------------------
+# Write @complain(FORMAT@,ARG1@,ARG2@,...@) to stdout.
+#
+# See b4_warn example.
+m4_define([b4_complain],
+[b4_error([[complain]], $@)])
+
+# b4_complain_at(START, END, FORMAT, [ARG1], [ARG2], ...)
+# -------------------------------------------------------
+# Write @complain(START@,END@,FORMAT@,ARG1@,ARG2@,...@) to stdout.
+#
+# See b4_warn_at example.
+m4_define([b4_complain_at],
+[b4_error_at([[complain]], $@)])
+
+# b4_fatal(FORMAT, [ARG1], [ARG2], ...)
+# -------------------------------------
+# Write @fatal(FORMAT@,ARG1@,ARG2@,...@) to stdout and exit.
+#
+# See b4_warn example.
+m4_define([b4_fatal],
+[b4_error([[fatal]], $@)dnl
+m4_exit(1)])
+
+# b4_fatal_at(START, END, FORMAT, [ARG1], [ARG2], ...)
+# ----------------------------------------------------
+# Write @fatal(START@,END@,FORMAT@,ARG1@,ARG2@,...@) to stdout and exit.
+#
+# See b4_warn_at example.
+m4_define([b4_fatal_at],
+[b4_error_at([[fatal]], $@)dnl
+m4_exit(1)])
+
+
+## ---------------- ##
+## Default values. ##
+## ---------------- ##
+
+# m4_define_default([b4_lex_param], []) dnl breaks other skeletons
+m4_define_default([b4_pre_prologue], [])
+m4_define_default([b4_post_prologue], [])
+m4_define_default([b4_epilogue], [])
+m4_define_default([b4_parse_param], [])
+
+# The initial column and line.
+m4_define_default([b4_location_initial_column], [1])
+m4_define_default([b4_location_initial_line], [1])
+
+
+## ------------ ##
+## Data Types. ##
+## ------------ ##
+
+# b4_ints_in(INT1, INT2, LOW, HIGH)
+# ---------------------------------
+# Return 1 iff both INT1 and INT2 are in [LOW, HIGH], 0 otherwise.
+m4_define([b4_ints_in],
+[m4_eval([$3 <= $1 && $1 <= $4 && $3 <= $2 && $2 <= $4])])
+
+
+
+## ------------------ ##
+## Decoding options. ##
+## ------------------ ##
+
+# b4_flag_if(FLAG, IF-TRUE, IF-FALSE)
+# -----------------------------------
+# Run IF-TRUE if b4_FLAG_flag is 1, IF-FALSE if FLAG is 0, otherwise fail.
+m4_define([b4_flag_if],
+[m4_case(b4_$1_flag,
+ [0], [$3],
+ [1], [$2],
+ [m4_fatal([invalid $1 value: ]$1)])])
+
+
+# b4_define_flag_if(FLAG)
+# -----------------------
+# Define "b4_FLAG_if(IF-TRUE, IF-FALSE)" that depends on the
+# value of the Boolean FLAG.
+m4_define([b4_define_flag_if],
+[_b4_define_flag_if($[1], $[2], [$1])])
+
+# _b4_define_flag_if($1, $2, FLAG)
+# --------------------------------
+# This macro works around the impossibility to define macros
+# inside macros, because issuing `[$1]' is not possible in M4 :(.
+# This sucks hard, GNU M4 should really provide M5 like $$1.
+m4_define([_b4_define_flag_if],
+[m4_if([$1$2], $[1]$[2], [],
+ [m4_fatal([$0: Invalid arguments: $@])])dnl
+m4_define([b4_$3_if],
+ [b4_flag_if([$3], [$1], [$2])])])
+
+
+# b4_FLAG_if(IF-TRUE, IF-FALSE)
+# -----------------------------
+# Expand IF-TRUE, if FLAG is true, IF-FALSE otherwise.
+b4_define_flag_if([defines]) # Whether headers are requested.
+b4_define_flag_if([error_verbose]) # Whether error are verbose.
+b4_define_flag_if([glr]) # Whether a GLR parser is requested.
+b4_define_flag_if([locations]) # Whether locations are tracked.
+b4_define_flag_if([nondeterministic]) # Whether conflicts should be handled.
+b4_define_flag_if([yacc]) # Whether POSIX Yacc is emulated.
+
+
+## ------------------------- ##
+## Assigning token numbers. ##
+## ------------------------- ##
+
+
+## ----------- ##
+## Synclines. ##
+## ----------- ##
+
+# b4_basename(NAME)
+# -----------------
+# Similar to POSIX basename; the differences don't matter here.
+# Beware that NAME is not evaluated.
+m4_define([b4_basename],
+[m4_bpatsubst([$1], [^.*/\([^/]+\)/*$], [\1])])
+
+
+# b4_syncline(LINE, FILE)
+# -----------------------
+m4_define([b4_syncline],
+[b4_flag_if([synclines], [
+b4_sync_end([__line__], [b4_basename(m4_quote(__file__))])
+b4_sync_start([$1], [$2])])])
+
+m4_define([b4_sync_end], [b4_comment([Line $1 of $2])])
+m4_define([b4_sync_start], [b4_comment([Line $1 of $2])])
+
+# b4_user_code(USER-CODE)
+# -----------------------
+# Emit code from the user, ending it with synclines.
+m4_define([b4_user_code],
+[$1
+b4_syncline([@oline@], [@ofile@])])
+
+
+# b4_define_user_code(MACRO)
+# --------------------------
+# From b4_MACRO, build b4_user_MACRO that includes the synclines.
+m4_define([b4_define_user_code],
+[m4_define([b4_user_$1],
+[b4_user_code([b4_$1])])])
+
+
+# b4_user_actions
+# b4_user_initial_action
+# b4_user_post_prologue
+# b4_user_pre_prologue
+# b4_user_stype
+# ----------------------
+# Macros that issue user code, ending with synclines.
+b4_define_user_code([actions])
+b4_define_user_code([initial_action])
+b4_define_user_code([post_prologue])
+b4_define_user_code([pre_prologue])
+b4_define_user_code([stype])
+
+
+# b4_check_user_names(WHAT, USER-LIST, BISON-NAMESPACE)
+# --------------------------------------------------------
+# Warn if any name of type WHAT is used by the user (as recorded in USER-LIST)
+# but is not used by Bison (as recorded by macros in the namespace
+# BISON-NAMESPACE).
+#
+# USER-LIST must expand to a list specifying all grammar occurrences of all
+# names of type WHAT. Each item in the list must be a triplet specifying one
+# occurrence: name, start boundary, and end boundary. Empty string names are
+# fine. An empty list is fine.
+#
+# For example, to define b4_foo_user_names to be used for USER-LIST with three
+# name occurrences and with correct quoting:
+#
+# m4_define([b4_foo_user_names],
+# [[[[[[bar]], [[parser.y:1.7]], [[parser.y:1.16]]]],
+# [[[[bar]], [[parser.y:5.7]], [[parser.y:5.16]]]],
+# [[[[baz]], [[parser.y:8.7]], [[parser.y:8.16]]]]]])
+#
+# The macro BISON-NAMESPACE(bar) must be defined iff the name bar of type WHAT
+# is used by Bison (in the front-end or in the skeleton). Empty string names
+# are fine, but it would be ugly for Bison to actually use one.
+#
+# For example, to use b4_foo_bison_names for BISON-NAMESPACE and define that
+# the names bar and baz are used by Bison:
+#
+# m4_define([b4_foo_bison_names(bar)])
+# m4_define([b4_foo_bison_names(baz)])
+#
+# To invoke b4_check_user_names with TYPE foo, with USER-LIST
+# b4_foo_user_names, with BISON-NAMESPACE b4_foo_bison_names, and with correct
+# quoting:
+#
+# b4_check_user_names([[foo]], [b4_foo_user_names],
+# [[b4_foo_bison_names]])
+m4_define([b4_check_user_names],
+[m4_foreach([b4_occurrence], $2,
+[m4_pushdef([b4_occurrence], b4_occurrence)dnl
+m4_pushdef([b4_user_name], m4_car(b4_occurrence))dnl
+m4_pushdef([b4_start], m4_car(m4_shift(b4_occurrence)))dnl
+m4_pushdef([b4_end], m4_shift(m4_shift(b4_occurrence)))dnl
+m4_ifndef($3[(]m4_quote(b4_user_name)[)],
+ [b4_warn_at([b4_start], [b4_end],
+ [[%s `%s' is not used]],
+ [$1], [b4_user_name])])[]dnl
+m4_popdef([b4_occurrence])dnl
+m4_popdef([b4_user_name])dnl
+m4_popdef([b4_start])dnl
+m4_popdef([b4_end])dnl
+])])
+
+# b4_percent_define_get(VARIABLE)
+# -------------------------------
+# Mimic muscle_percent_define_get in ../src/muscle_tab.h exactly. That is, if
+# the %define variable VARIABLE is defined, emit its value. Also, record
+# Bison's usage of VARIABLE by defining
+# b4_percent_define_bison_variables(VARIABLE).
+#
+# For example:
+#
+# b4_percent_define_get([[foo]])
+m4_define([b4_percent_define_get],
+[m4_define([b4_percent_define_bison_variables(]$1[)])dnl
+m4_ifdef([b4_percent_define(]$1[)], [m4_indir([b4_percent_define(]$1[)])])])
+
+# b4_percent_define_get_loc(VARIABLE)
+# -----------------------------------
+# Mimic muscle_percent_define_get_loc in ../src/muscle_tab.h exactly. That is,
+# if the %define variable VARIABLE is undefined, complain fatally since that's
+# a Bison or skeleton error. Otherwise, return its definition location in a
+# form approriate for the first two arguments of b4_warn_at, b4_complain_at, or
+# b4_fatal_at. Don't record this as a Bison usage of VARIABLE as there's no
+# reason to suspect that the user-supplied value has yet influenced the output.
+#
+# For example:
+#
+# b4_complain_at(b4_percent_define_get_loc([[foo]]), [[invalid foo]])
+m4_define([b4_percent_define_get_loc],
+[m4_ifdef([b4_percent_define_loc(]$1[)],
+ [m4_pushdef([b4_loc], m4_indir([b4_percent_define_loc(]$1[)]))dnl
+b4_loc[]dnl
+m4_popdef([b4_loc])],
+ [b4_fatal([[undefined %%define variable `%s' passed to b4_percent_define_get_loc]], [$1])])])
+
+# b4_percent_define_get_syncline(VARIABLE)
+# ----------------------------------------
+# Mimic muscle_percent_define_get_syncline in ../src/muscle_tab.h exactly.
+# That is, if the %define variable VARIABLE is undefined, complain fatally
+# since that's a Bison or skeleton error. Otherwise, return its definition
+# location as a b4_syncline invocation. Don't record this as a Bison usage of
+# VARIABLE as there's no reason to suspect that the user-supplied value has yet
+# influenced the output.
+#
+# For example:
+#
+# b4_percent_define_get_syncline([[foo]])
+m4_define([b4_percent_define_get_syncline],
+[m4_ifdef([b4_percent_define_syncline(]$1[)],
+ [m4_indir([b4_percent_define_syncline(]$1[)])],
+ [b4_fatal([[undefined %%define variable `%s' passed to b4_percent_define_get_syncline]], [$1])])])
+
+# b4_percent_define_ifdef(VARIABLE, IF-TRUE, [IF-FALSE])
+# ------------------------------------------------------
+# Mimic muscle_percent_define_ifdef in ../src/muscle_tab.h exactly. That is,
+# if the %define variable VARIABLE is defined, expand IF-TRUE, else expand
+# IF-FALSE. Also, record Bison's usage of VARIABLE by defining
+# b4_percent_define_bison_variables(VARIABLE).
+#
+# For example:
+#
+# b4_percent_define_ifdef([[foo]], [[it's defined]], [[it's undefined]])
+m4_define([b4_percent_define_ifdef],
+[m4_ifdef([b4_percent_define(]$1[)],
+ [m4_define([b4_percent_define_bison_variables(]$1[)])$2],
+ [$3])])
+
+# b4_percent_define_flag_if(VARIABLE, IF-TRUE, [IF-FALSE])
+# --------------------------------------------------------
+# Mimic muscle_percent_define_flag_if in ../src/muscle_tab.h exactly. That is,
+# if the %define variable VARIABLE is defined to "" or "true", expand IF-TRUE.
+# If it is defined to "false", expand IF-FALSE. Complain if it is undefined
+# (a Bison or skeleton error since the default value should have been set
+# already) or defined to any other value (possibly a user error). Also, record
+# Bison's usage of VARIABLE by defining
+# b4_percent_define_bison_variables(VARIABLE).
+#
+# For example:
+#
+# b4_percent_define_flag_if([[foo]], [[it's true]], [[it's false]])
+m4_define([b4_percent_define_flag_if],
+[b4_percent_define_ifdef([$1],
+ [m4_case(b4_percent_define_get([$1]),
+ [], [$2], [true], [$2], [false], [$3],
+ [m4_expand_once([b4_complain_at(b4_percent_define_get_loc([$1]),
+ [[invalid value for %%define Boolean variable `%s']],
+ [$1])],
+ [[b4_percent_define_flag_if($1)]])])],
+ [b4_fatal([[undefined %%define variable `%s' passed to b4_percent_define_flag_if]], [$1])])])
+
+# b4_percent_define_default(VARIABLE, DEFAULT)
+# --------------------------------------------
+# Mimic muscle_percent_define_default in ../src/muscle_tab.h exactly. That is,
+# if the %define variable VARIABLE is undefined, set its value to DEFAULT.
+# Don't record this as a Bison usage of VARIABLE as there's no reason to
+# suspect that the value has yet influenced the output.
+#
+# For example:
+#
+# b4_percent_define_default([[foo]], [[default value]])
+m4_define([b4_percent_define_default],
+[m4_ifndef([b4_percent_define(]$1[)],
+ [m4_define([b4_percent_define(]$1[)], [$2])dnl
+ m4_define([b4_percent_define_loc(]$1[)],
+ [[[[[Bison:b4_percent_define_default]:1.0]], [[[Bison:b4_percent_define_default]:1.0]]]])dnl
+ m4_define([b4_percent_define_syncline(]$1[)],
+ [[]b4_syncline(1, [["[Bison:b4_percent_define_default]"]])[
+]])])])
+
+# b4_percent_define_check_values(VALUES)
+# --------------------------------------
+# Mimic muscle_percent_define_check_values in ../src/muscle_tab.h exactly
+# except that the VALUES structure is more appropriate for M4. That is, VALUES
+# is a list of sublists of strings. For each sublist, the first string is the
+# name of a %define variable, and all remaining strings in that sublist are the
+# valid values for that variable. Complain if such a variable is undefined (a
+# Bison error since the default value should have been set already) or defined
+# to any other value (possibly a user error). Don't record this as a Bison
+# usage of the variable as there's no reason to suspect that the value has yet
+# influenced the output.
+#
+# For example:
+#
+# b4_percent_define_check_values([[[[foo]], [[foo-value1]], [[foo-value2]]]],
+# [[[[bar]], [[bar-value1]]]])
+m4_define([b4_percent_define_check_values],
+[m4_foreach([b4_sublist], m4_quote($@),
+ [_b4_percent_define_check_values(b4_sublist)])])
+
+m4_define([_b4_percent_define_check_values],
+[m4_ifdef([b4_percent_define(]$1[)],
+ [m4_pushdef([b4_good_value], [0])dnl
+ m4_if($#, 1, [],
+ [m4_foreach([b4_value], m4_dquote(m4_shift($@)),
+ [m4_if(m4_indir([b4_percent_define(]$1[)]), b4_value,
+ [m4_define([b4_good_value], [1])])])])dnl
+ m4_if(b4_good_value, [0],
+ [b4_complain_at(b4_percent_define_get_loc([$1]),
+ [[invalid value for %%define variable `%s': `%s']],
+ [$1],
+ m4_dquote(m4_indir([b4_percent_define(]$1[)])))])dnl
+ m4_popdef([b4_good_value])],
+ [b4_fatal([[undefined %%define variable `%s' passed to b4_percent_define_check_values]], [$1])])])
+
+# b4_percent_code_get([QUALIFIER])
+# --------------------------------
+# If any %code blocks for QUALIFIER are defined, emit them beginning with a
+# comment and ending with synclines and a newline. If QUALIFIER is not
+# specified or empty, do this for the unqualified %code blocks. Also, record
+# Bison's usage of QUALIFIER (if specified) by defining
+# b4_percent_code_bison_qualifiers(QUALIFIER).
+#
+# For example, to emit any unqualified %code blocks followed by any %code
+# blocks for the qualifier foo:
+#
+# b4_percent_code_get
+# b4_percent_code_get([[foo]])
+m4_define([b4_percent_code_get],
+[m4_pushdef([b4_macro_name], [[b4_percent_code(]$1[)]])dnl
+m4_ifval([$1], [m4_define([b4_percent_code_bison_qualifiers(]$1[)])])dnl
+m4_ifdef(b4_macro_name,
+[b4_comment([m4_if([$#], [0], [[Unqualified %code]],
+ [["%code ]$1["]])[ blocks.]])
+b4_user_code([m4_indir(b4_macro_name)])
+])dnl
+m4_popdef([b4_macro_name])])
+
+# b4_percent_code_ifdef(QUALIFIER, IF-TRUE, [IF-FALSE])
+# -----------------------------------------------------
+# If any %code blocks for QUALIFIER (or unqualified %code blocks if
+# QUALIFIER is empty) are defined, expand IF-TRUE, else expand IF-FALSE.
+# Also, record Bison's usage of QUALIFIER (if specified) by defining
+# b4_percent_code_bison_qualifiers(QUALIFIER).
+m4_define([b4_percent_code_ifdef],
+[m4_ifdef([b4_percent_code(]$1[)],
+ [m4_ifval([$1], [m4_define([b4_percent_code_bison_qualifiers(]$1[)])])$2],
+ [$3])])
+
+
+## ----------------------------------------------------------- ##
+## After processing the skeletons, check that all the user's ##
+## %define variables and %code qualifiers were used by Bison. ##
+## ----------------------------------------------------------- ##
+
+m4_define([b4_check_user_names_wrap],
+[m4_ifdef([b4_percent_]$1[_user_]$2[s],
+ [b4_check_user_names([[%]$1 $2],
+ [b4_percent_]$1[_user_]$2[s],
+ [[b4_percent_]$1[_bison_]$2[s]])])])
+
+m4_wrap_lifo([
+b4_check_user_names_wrap([[define]], [[variable]])
+b4_check_user_names_wrap([[code]], [[qualifier]])
+])
diff --git a/tools/mhmake/src/bisondata/c++.m4 b/tools/mhmake/src/bisondata/c++.m4
new file mode 100644
index 000000000..a27064d7b
--- /dev/null
+++ b/tools/mhmake/src/bisondata/c++.m4
@@ -0,0 +1,170 @@
+ -*- Autoconf -*-
+
+# C++ skeleton for Bison
+
+# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation,
+# Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+m4_include(b4_pkgdatadir/[c.m4])
+
+## ---------------- ##
+## Default values. ##
+## ---------------- ##
+
+# Default parser class name.
+b4_percent_define_default([[parser_class_name]], [[parser]])
+b4_percent_define_default([[location_type]], [[location]])
+b4_percent_define_default([[filename_type]], [[std::string]])
+b4_percent_define_default([[namespace]], m4_defn([b4_prefix]))
+b4_percent_define_default([[global_tokens_and_yystype]], [[false]])
+b4_percent_define_default([[define_location_comparison]],
+ [m4_if(b4_percent_define_get([[filename_type]]),
+ [std::string], [[true]], [[false]])])
+
+
+## ----------- ##
+## Namespace. ##
+## ----------- ##
+
+m4_define([b4_namespace_ref], [b4_percent_define_get([[namespace]])])
+
+# Don't permit an empty b4_namespace_ref. Any `::parser::foo' appended to it
+# would compile as an absolute reference with `parser' in the global namespace.
+# b4_namespace_open would open an anonymous namespace and thus establish
+# internal linkage. This would compile. However, it's cryptic, and internal
+# linkage for the parser would be specified in all translation units that
+# include the header, which is always generated. If we ever need to permit
+# internal linkage somehow, surely we can find a cleaner approach.
+m4_if(m4_bregexp(b4_namespace_ref, [^[ ]*$]), [-1], [],
+[b4_complain_at(b4_percent_define_get_loc([[namespace]]),
+ [[namespace reference is empty]])])
+
+# Instead of assuming the C++ compiler will do it, Bison should reject any
+# invalid b4_namepsace_ref that would be converted to a valid
+# b4_namespace_open. The problem is that Bison doesn't always output
+# b4_namespace_ref to uncommented code but should reserve the ability to do so
+# in future releases without risking breaking any existing user grammars.
+# Specifically, don't allow empty names as b4_namespace_open would just convert
+# those into anonymous namespaces, and that might tempt some users.
+m4_if(m4_bregexp(b4_namespace_ref, [::[ ]*::]), [-1], [],
+[b4_complain_at(b4_percent_define_get_loc([[namespace]]),
+ [[namespace reference has consecutive "::"]])])
+m4_if(m4_bregexp(b4_namespace_ref, [::[ ]*$]), [-1], [],
+[b4_complain_at(b4_percent_define_get_loc([[namespace]]),
+ [[namespace reference has a trailing "::"]])])
+
+m4_define([b4_namespace_open],
+[b4_user_code([b4_percent_define_get_syncline([[namespace]])
+[namespace ]m4_bpatsubst(m4_dquote(m4_bpatsubst(m4_dquote(b4_namespace_ref),
+ [^\(.\)[ ]*::], [\1])),
+ [::], [ { namespace ])[ {]])])
+
+m4_define([b4_namespace_close],
+[b4_user_code([b4_percent_define_get_syncline([[namespace]])
+m4_bpatsubst(m4_dquote(m4_bpatsubst(m4_dquote(b4_namespace_ref),
+ [^\(.\)[ ]*\(::\)?\([^][:]\|:[^][:]\)*],
+ [\1])),
+ [::\([^][:]\|:[^][:]\)*], [} ])[} // ]b4_namespace_ref])])
+
+
+# b4_token_enums(LIST-OF-PAIRS-TOKEN-NAME-TOKEN-NUMBER)
+# -----------------------------------------------------
+# Output the definition of the tokens as enums.
+m4_define([b4_token_enums],
+[/* Tokens. */
+ enum yytokentype {
+m4_map_sep([ b4_token_enum], [,
+],
+ [$@])
+ };
+])
+
+
+## ----------------- ##
+## Semantic Values. ##
+## ----------------- ##
+
+
+# b4_lhs_value([TYPE])
+# --------------------
+# Expansion of $<TYPE>$.
+m4_define([b4_lhs_value],
+[(yyval[]m4_ifval([$1], [.$1]))])
+
+
+# b4_rhs_value(RULE-LENGTH, NUM, [TYPE])
+# --------------------------------------
+# Expansion of $<TYPE>NUM, where the current rule has RULE-LENGTH
+# symbols on RHS.
+m4_define([b4_rhs_value],
+[(yysemantic_stack_@{($1) - ($2)@}m4_ifval([$3], [.$3]))])
+
+# b4_lhs_location()
+# -----------------
+# Expansion of @$.
+m4_define([b4_lhs_location],
+[(yyloc)])
+
+
+# b4_rhs_location(RULE-LENGTH, NUM)
+# ---------------------------------
+# Expansion of @NUM, where the current rule has RULE-LENGTH symbols
+# on RHS.
+m4_define([b4_rhs_location],
+[(yylocation_stack_@{($1) - ($2)@})])
+
+
+# b4_parse_param_decl
+# -------------------
+# Extra formal arguments of the constructor.
+# Change the parameter names from "foo" into "foo_yyarg", so that
+# there is no collision bw the user chosen attribute name, and the
+# argument name in the constructor.
+m4_define([b4_parse_param_decl],
+[m4_ifset([b4_parse_param],
+ [m4_map_sep([b4_parse_param_decl_1], [, ], [b4_parse_param])])])
+
+m4_define([b4_parse_param_decl_1],
+[$1_yyarg])
+
+
+
+# b4_parse_param_cons
+# -------------------
+# Extra initialisations of the constructor.
+m4_define([b4_parse_param_cons],
+ [m4_ifset([b4_parse_param],
+ [
+ b4_cc_constructor_calls(b4_parse_param)])])
+m4_define([b4_cc_constructor_calls],
+ [m4_map_sep([b4_cc_constructor_call], [,
+ ], [$@])])
+m4_define([b4_cc_constructor_call],
+ [$2 ($2_yyarg)])
+
+# b4_parse_param_vars
+# -------------------
+# Extra instance variables.
+m4_define([b4_parse_param_vars],
+ [m4_ifset([b4_parse_param],
+ [
+ /* User arguments. */
+b4_cc_var_decls(b4_parse_param)])])
+m4_define([b4_cc_var_decls],
+ [m4_map_sep([b4_cc_var_decl], [
+], [$@])])
+m4_define([b4_cc_var_decl],
+ [ $1;])
diff --git a/tools/mhmake/src/bisondata/c-skel.m4 b/tools/mhmake/src/bisondata/c-skel.m4
new file mode 100644
index 000000000..91f3c2052
--- /dev/null
+++ b/tools/mhmake/src/bisondata/c-skel.m4
@@ -0,0 +1,25 @@
+ -*- Autoconf -*-
+
+# C skeleton dispatching for Bison.
+# Copyright (C) 2006, 2007 Free Software Foundation, Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+b4_glr_if( [m4_define([b4_used_skeleton], [b4_pkgdatadir/[glr.c]])])
+b4_nondeterministic_if([m4_define([b4_used_skeleton], [b4_pkgdatadir/[glr.c]])])
+
+m4_define_default([b4_used_skeleton], [b4_pkgdatadir/[yacc.c]])
+m4_define_default([b4_skeleton], ["b4_basename(b4_used_skeleton)"])
+
+m4_include(b4_used_skeleton)
diff --git a/tools/mhmake/src/bisondata/c.m4 b/tools/mhmake/src/bisondata/c.m4
new file mode 100644
index 000000000..2b44b7e49
--- /dev/null
+++ b/tools/mhmake/src/bisondata/c.m4
@@ -0,0 +1,477 @@
+ -*- Autoconf -*-
+
+# C M4 Macros for Bison.
+# Copyright (C) 2002, 2004, 2005, 2006, 2007, 2008 Free Software
+# Foundation, Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+## ---------------- ##
+## Identification. ##
+## ---------------- ##
+
+# b4_comment(TEXT)
+# ----------------
+m4_define([b4_comment], [/* m4_bpatsubst([$1], [
+], [
+ ]) */])
+
+# b4_identification
+# -----------------
+# Depends on individual skeletons to define b4_pure_flag, b4_push_flag, or
+# b4_pull_flag if they use the values of the %define variables api.pure or
+# api.push_pull.
+m4_define([b4_identification],
+[[/* Identify Bison output. */
+#define YYBISON 1
+
+/* Bison version. */
+#define YYBISON_VERSION "]b4_version["
+
+/* Skeleton name. */
+#define YYSKELETON_NAME ]b4_skeleton[]m4_ifdef([b4_pure_flag], [[
+
+/* Pure parsers. */
+#define YYPURE ]b4_pure_flag])[]m4_ifdef([b4_push_flag], [[
+
+/* Push parsers. */
+#define YYPUSH ]b4_push_flag])[]m4_ifdef([b4_pull_flag], [[
+
+/* Pull parsers. */
+#define YYPULL ]b4_pull_flag])[
+
+/* Using locations. */
+#define YYLSP_NEEDED ]b4_locations_flag[
+]])
+
+
+## ---------------- ##
+## Default values. ##
+## ---------------- ##
+
+# If the %union is not named, its name is YYSTYPE.
+m4_define_default([b4_union_name], [YYSTYPE])
+
+# If the %name-prefix is not given, it is yy.
+m4_define_default([b4_prefix], [yy])
+
+## ------------------------ ##
+## Pure/impure interfaces. ##
+## ------------------------ ##
+
+# b4_user_args
+# ------------
+m4_define([b4_user_args],
+[m4_ifset([b4_parse_param], [, b4_c_args(b4_parse_param)])])
+
+
+# b4_parse_param
+# --------------
+# If defined, b4_parse_param arrives double quoted, but below we prefer
+# it to be single quoted.
+m4_define([b4_parse_param],
+b4_parse_param)
+
+
+# b4_parse_param_for(DECL, FORMAL, BODY)
+# ---------------------------------------
+# Iterate over the user parameters, binding the declaration to DECL,
+# the formal name to FORMAL, and evaluating the BODY.
+m4_define([b4_parse_param_for],
+[m4_foreach([$1_$2], m4_defn([b4_parse_param]),
+[m4_pushdef([$1], m4_unquote(m4_car($1_$2)))dnl
+m4_pushdef([$2], m4_shift($1_$2))dnl
+$3[]dnl
+m4_popdef([$2])dnl
+m4_popdef([$1])dnl
+])])
+
+# b4_parse_param_use
+# ------------------
+# `YYUSE' all the parse-params.
+m4_define([b4_parse_param_use],
+[b4_parse_param_for([Decl], [Formal], [ YYUSE (Formal);
+])dnl
+])
+
+
+## ------------ ##
+## Data Types. ##
+## ------------ ##
+
+# b4_int_type(MIN, MAX)
+# ---------------------
+# Return the smallest int type able to handle numbers ranging from
+# MIN to MAX (included).
+m4_define([b4_int_type],
+[m4_if(b4_ints_in($@, [0], [255]), [1], [unsigned char],
+ b4_ints_in($@, [-128], [127]), [1], [signed char],
+
+ b4_ints_in($@, [0], [65535]), [1], [unsigned short int],
+ b4_ints_in($@, [-32768], [32767]), [1], [short int],
+
+ m4_eval([0 <= $1]), [1], [unsigned int],
+
+ [int])])
+
+
+# b4_int_type_for(NAME)
+# ---------------------
+# Return the smallest int type able to handle numbers ranging from
+# `NAME_min' to `NAME_max' (included).
+m4_define([b4_int_type_for],
+[b4_int_type($1_min, $1_max)])
+
+
+
+## ---------##
+## Values. ##
+## ---------##
+
+# b4_null
+---------
+# Return a null pointer constant. NULL infringes on the user name
+# space in C, so use 0 rather than NULL.
+m4_define([b4_null], [0])
+
+
+
+
+## ------------------------- ##
+## Assigning token numbers. ##
+## ------------------------- ##
+
+# b4_token_define(TOKEN-NAME, TOKEN-NUMBER)
+# -----------------------------------------
+# Output the definition of this token as #define.
+m4_define([b4_token_define],
+[#define $1 $2
+])
+
+
+# b4_token_defines(LIST-OF-PAIRS-TOKEN-NAME-TOKEN-NUMBER)
+# -------------------------------------------------------
+# Output the definition of the tokens (if there are) as #defines.
+m4_define([b4_token_defines],
+[m4_if([$#$1], [1], [],
+[/* Tokens. */
+m4_map([b4_token_define], [$@])])
+])
+
+
+# b4_token_enum(TOKEN-NAME, TOKEN-NUMBER)
+# ---------------------------------------
+# Output the definition of this token as an enum.
+m4_define([b4_token_enum],
+[$1 = $2])
+
+
+# b4_token_enums(LIST-OF-PAIRS-TOKEN-NAME-TOKEN-NUMBER)
+# -----------------------------------------------------
+# Output the definition of the tokens (if there are) as enums.
+m4_define([b4_token_enums],
+[m4_if([$#$1], [1], [],
+[/* Tokens. */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+ /* Put the tokens into the symbol table, so that GDB and other debuggers
+ know about them. */
+ enum yytokentype {
+m4_map_sep([ b4_token_enum], [,
+],
+ [$@])
+ };
+#endif
+])])
+
+
+# b4_token_enums_defines(LIST-OF-PAIRS-TOKEN-NAME-TOKEN-NUMBER)
+# -------------------------------------------------------------
+# Output the definition of the tokens (if there are any) as enums and, if POSIX
+# Yacc is enabled, as #defines.
+m4_define([b4_token_enums_defines],
+[b4_token_enums($@)b4_yacc_if([b4_token_defines($@)], [])
+])
+
+
+
+## --------------------------------------------- ##
+## Defining C functions in both K&R and ANSI-C. ##
+## --------------------------------------------- ##
+
+
+# b4_modern_c
+# -----------
+# A predicate useful in #if to determine whether C is ancient or modern.
+#
+# If __STDC__ is defined, the compiler is modern. IBM xlc 7.0 when run
+# as 'cc' doesn't define __STDC__ (or __STDC_VERSION__) for pedantic
+# reasons, but it defines __C99__FUNC__ so check that as well.
+# Microsoft C normally doesn't define these macros, but it defines _MSC_VER.
+# Consider a C++ compiler to be modern if it defines __cplusplus.
+#
+m4_define([b4_c_modern],
+ [[(defined __STDC__ || defined __C99__FUNC__ \
+ || defined __cplusplus || defined _MSC_VER)]])
+
+# b4_c_function_def(NAME, RETURN-VALUE, [DECL1, NAME1], ...)
+# ----------------------------------------------------------
+# Declare the function NAME.
+m4_define([b4_c_function_def],
+[#if b4_c_modern
+b4_c_ansi_function_def($@)
+#else
+$2
+$1 (b4_c_knr_formal_names(m4_shift2($@)))
+b4_c_knr_formal_decls(m4_shift2($@))
+#endif[]dnl
+])
+
+
+# b4_c_ansi_function_def(NAME, RETURN-VALUE, [DECL1, NAME1], ...)
+# ---------------------------------------------------------------
+# Declare the function NAME in ANSI.
+m4_define([b4_c_ansi_function_def],
+[$2
+$1 (b4_c_ansi_formals(m4_shift2($@)))[]dnl
+])
+
+
+# b4_c_ansi_formals([DECL1, NAME1], ...)
+# --------------------------------------
+# Output the arguments ANSI-C definition.
+m4_define([b4_c_ansi_formals],
+[m4_if([$#], [0], [void],
+ [$#$1], [1], [void],
+ [m4_map_sep([b4_c_ansi_formal], [, ], [$@])])])
+
+m4_define([b4_c_ansi_formal],
+[$1])
+
+
+# b4_c_knr_formal_names([DECL1, NAME1], ...)
+# ------------------------------------------
+# Output the argument names.
+m4_define([b4_c_knr_formal_names],
+[m4_map_sep([b4_c_knr_formal_name], [, ], [$@])])
+
+m4_define([b4_c_knr_formal_name],
+[$2])
+
+
+# b4_c_knr_formal_decls([DECL1, NAME1], ...)
+# ------------------------------------------
+# Output the K&R argument declarations.
+m4_define([b4_c_knr_formal_decls],
+[m4_map_sep([b4_c_knr_formal_decl],
+ [
+],
+ [$@])])
+
+m4_define([b4_c_knr_formal_decl],
+[ $1;])
+
+
+
+## ------------------------------------------------------------ ##
+## Declaring (prototyping) C functions in both K&R and ANSI-C. ##
+## ------------------------------------------------------------ ##
+
+
+# b4_c_function_decl(NAME, RETURN-VALUE, [DECL1, NAME1], ...)
+# -----------------------------------------------------------
+# Declare the function NAME.
+m4_define([b4_c_function_decl],
+[#if defined __STDC__ || defined __cplusplus
+b4_c_ansi_function_decl($@)
+#else
+$2 $1 ();
+#endif[]dnl
+])
+
+
+# b4_c_ansi_function_decl(NAME, RETURN-VALUE, [DECL1, NAME1], ...)
+# ----------------------------------------------------------------
+# Declare the function NAME.
+m4_define([b4_c_ansi_function_decl],
+[$2 $1 (b4_c_ansi_formals(m4_shift2($@)));[]dnl
+])
+
+
+
+
+## --------------------- ##
+## Calling C functions. ##
+## --------------------- ##
+
+
+# b4_c_function_call(NAME, RETURN-VALUE, [DECL1, NAME1], ...)
+# -----------------------------------------------------------
+# Call the function NAME with arguments NAME1, NAME2 etc.
+m4_define([b4_c_function_call],
+[$1 (b4_c_args(m4_shift2($@)))[]dnl
+])
+
+
+# b4_c_args([DECL1, NAME1], ...)
+# ------------------------------
+# Output the arguments NAME1, NAME2...
+m4_define([b4_c_args],
+[m4_map_sep([b4_c_arg], [, ], [$@])])
+
+m4_define([b4_c_arg],
+[$2])
+
+
+## ----------- ##
+## Synclines. ##
+## ----------- ##
+
+# b4_sync_start(LINE, FILE)
+# -----------------------
+m4_define([b4_sync_start], [[#]line $1 $2])
+
+
+## -------------- ##
+## User actions. ##
+## -------------- ##
+
+# b4_case(LABEL, STATEMENTS)
+# --------------------------
+m4_define([b4_case],
+[ case $1:
+$2
+ break;])
+
+# b4_symbol_actions(FILENAME, LINENO,
+# SYMBOL-TAG, SYMBOL-NUM,
+# SYMBOL-ACTION, SYMBOL-TYPENAME)
+# -------------------------------------------------
+m4_define([b4_symbol_actions],
+[m4_pushdef([b4_dollar_dollar],
+ [m4_ifval([$6], [(yyvaluep->$6)], [(*yyvaluep)])])dnl
+m4_pushdef([b4_at_dollar], [(*yylocationp)])dnl
+ case $4: /* $3 */
+b4_syncline([$2], [$1])
+ $5;
+b4_syncline([@oline@], [@ofile@])
+ break;
+m4_popdef([b4_at_dollar])dnl
+m4_popdef([b4_dollar_dollar])dnl
+])
+
+
+# b4_yydestruct_generate(FUNCTION-DECLARATOR)
+# -------------------------------------------
+# Generate the "yydestruct" function, which declaration is issued using
+# FUNCTION-DECLARATOR, which may be "b4_c_ansi_function_def" for ISO C
+# or "b4_c_function_def" for K&R.
+m4_define_default([b4_yydestruct_generate],
+[[/*-----------------------------------------------.
+| Release the memory associated to this symbol. |
+`-----------------------------------------------*/
+
+/*ARGSUSED*/
+]$1([yydestruct],
+ [static void],
+ [[const char *yymsg], [yymsg]],
+ [[int yytype], [yytype]],
+ [[YYSTYPE *yyvaluep], [yyvaluep]][]dnl
+b4_locations_if( [, [[YYLTYPE *yylocationp], [yylocationp]]])[]dnl
+m4_ifset([b4_parse_param], [, b4_parse_param]))[
+{
+ YYUSE (yyvaluep);
+]b4_locations_if([ YYUSE (yylocationp);
+])dnl
+b4_parse_param_use[]dnl
+[
+ if (!yymsg)
+ yymsg = "Deleting";
+ YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
+
+ switch (yytype)
+ {
+]m4_map([b4_symbol_actions], m4_defn([b4_symbol_destructors]))[
+ default:
+ break;
+ }
+}]dnl
+])
+
+
+# b4_yy_symbol_print_generate(FUNCTION-DECLARATOR)
+# ------------------------------------------------
+# Generate the "yy_symbol_print" function, which declaration is issued using
+# FUNCTION-DECLARATOR, which may be "b4_c_ansi_function_def" for ISO C
+# or "b4_c_function_def" for K&R.
+m4_define_default([b4_yy_symbol_print_generate],
+[[
+/*--------------------------------.
+| Print this symbol on YYOUTPUT. |
+`--------------------------------*/
+
+/*ARGSUSED*/
+]$1([yy_symbol_value_print],
+ [static void],
+ [[FILE *yyoutput], [yyoutput]],
+ [[int yytype], [yytype]],
+ [[YYSTYPE const * const yyvaluep], [yyvaluep]][]dnl
+b4_locations_if([, [[YYLTYPE const * const yylocationp], [yylocationp]]])[]dnl
+m4_ifset([b4_parse_param], [, b4_parse_param]))[
+{
+ if (!yyvaluep)
+ return;
+]b4_locations_if([ YYUSE (yylocationp);
+])dnl
+b4_parse_param_use[]dnl
+[# ifdef YYPRINT
+ if (yytype < YYNTOKENS)
+ YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
+# else
+ YYUSE (yyoutput);
+# endif
+ switch (yytype)
+ {
+]m4_map([b4_symbol_actions], m4_defn([b4_symbol_printers]))dnl
+[ default:
+ break;
+ }
+}
+
+
+/*--------------------------------.
+| Print this symbol on YYOUTPUT. |
+`--------------------------------*/
+
+]$1([yy_symbol_print],
+ [static void],
+ [[FILE *yyoutput], [yyoutput]],
+ [[int yytype], [yytype]],
+ [[YYSTYPE const * const yyvaluep], [yyvaluep]][]dnl
+b4_locations_if([, [[YYLTYPE const * const yylocationp], [yylocationp]]])[]dnl
+m4_ifset([b4_parse_param], [, b4_parse_param]))[
+{
+ if (yytype < YYNTOKENS)
+ YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
+ else
+ YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
+
+]b4_locations_if([ YY_LOCATION_PRINT (yyoutput, *yylocationp);
+ YYFPRINTF (yyoutput, ": ");
+])dnl
+[ yy_symbol_value_print (yyoutput, yytype, yyvaluep]dnl
+b4_locations_if([, yylocationp])[]b4_user_args[);
+ YYFPRINTF (yyoutput, ")");
+}]dnl
+])
diff --git a/tools/mhmake/src/bisondata/lalr1.cc b/tools/mhmake/src/bisondata/lalr1.cc
new file mode 100644
index 000000000..fdc033a1d
--- /dev/null
+++ b/tools/mhmake/src/bisondata/lalr1.cc
@@ -0,0 +1,1174 @@
+# C++ skeleton for Bison
+
+# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
+# Free Software Foundation, Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+m4_include(b4_pkgdatadir/[c++.m4])
+
+m4_define([b4_parser_class_name],
+ [b4_percent_define_get([[parser_class_name]])])
+
+m4_define([b4_parser_base_class_name],
+ [b4_percent_define_get([[parser_base_class_name]])])
+
+m4_define([b4_parser_class_constructor_init],
+ [b4_percent_define_get([[parser_class_constructor_init]])])
+
+m4_define([b4_parser_class_constructor_param],
+ [b4_percent_define_get([[parser_class_constructor_param]])])
+
+# The header is mandatory.
+b4_defines_if([],
+ [b4_fatal([b4_skeleton[: using %%defines is mandatory]])])
+
+# Backward compatibility.
+m4_define([b4_location_constructors])
+m4_include(b4_pkgdatadir/[location.cc])
+
+# We do want M4 expansion after # for CPP macros.
+m4_changecom()
+m4_divert_push(0)dnl
+b4_defines_if(
+[@output(b4_spec_defines_file@)
+b4_copyright([Skeleton interface for Bison LALR(1) parsers in C++],
+ [2002, 2003, 2004, 2005, 2006, 2007, 2008])
+dnl FIXME: This is wrong, we want computed header guards.
+[
+/* C++ LALR(1) parser skeleton written by Akim Demaille. */
+
+#ifndef PARSER_HEADER_H
+# define PARSER_HEADER_H
+
+]b4_percent_code_get([[requires]])[
+
+#include <string>
+#include <iostream>
+#include "stack.hh"
+
+]b4_namespace_open[
+ class position;
+ class location;
+]b4_namespace_close[
+
+#include "location.hh"
+
+/* Enabling traces. */
+#ifndef YYDEBUG
+# define YYDEBUG ]b4_debug_flag[
+#endif
+
+/* Enabling verbose error messages. */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE ]b4_error_verbose_flag[
+#endif
+
+/* Enabling the token table. */
+#ifndef YYTOKEN_TABLE
+# define YYTOKEN_TABLE ]b4_token_table[
+#endif
+
+/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
+ If N is 0, then set CURRENT to the empty location which ends
+ the previous symbol: RHS[0] (always defined). */
+
+#ifndef YYLLOC_DEFAULT
+# define YYLLOC_DEFAULT(Current, Rhs, N) \
+do { \
+ if (N) \
+ { \
+ (Current).begin = (Rhs)[1].begin; \
+ (Current).end = (Rhs)[N].end; \
+ } \
+ else \
+ { \
+ (Current).begin = (Current).end = (Rhs)[0].end; \
+ } \
+} while (false)
+#endif
+
+]b4_namespace_open[
+
+ /// A Bison parser.
+ class ]b4_parser_class_name[ : public ]b4_parser_base_class_name[
+ {
+ public:
+ /// Symbol semantic values.
+#ifndef YYSTYPE
+]m4_ifdef([b4_stype],
+[ union semantic_type
+ {
+b4_user_stype
+ };],
+[m4_if(b4_tag_seen_flag, 0,
+[[ typedef int semantic_type;]],
+[[ typedef YYSTYPE semantic_type;]])])[
+#else
+ typedef YYSTYPE semantic_type;
+#endif
+ /// Symbol locations.
+ typedef ]b4_percent_define_get([[location_type]])[ location_type;
+ /// Tokens.
+ struct token
+ {
+ ]b4_token_enums(b4_tokens)[
+ };
+ /// Token type.
+ typedef token::yytokentype token_type;
+
+ /// Build a parser object.
+ ]b4_parser_class_name[ (]b4_parse_param_decl[ ]b4_parser_class_constructor_param[ );
+ virtual ~]b4_parser_class_name[ ();
+
+ /// Parse.
+ /// \returns 0 iff parsing succeeded.
+ virtual int parse ();
+
+#if YYDEBUG
+ /// The current debugging stream.
+ std::ostream& debug_stream () const;
+ /// Set the current debugging stream.
+ void set_debug_stream (std::ostream &);
+
+ /// Type for debugging levels.
+ typedef int debug_level_type;
+ /// The current debugging level.
+ debug_level_type debug_level () const;
+ /// Set the current debugging level.
+ void set_debug_level (debug_level_type l);
+#endif
+
+ position *GetCurPos(void)
+ {
+ return &yylocation_stack_[1].begin;
+ }
+
+ private:
+ /// Report a syntax error.
+ /// \param loc where the syntax error is found.
+ /// \param msg a description of the syntax error.
+ virtual void error (const location_type& loc, const std::string& msg);
+
+ /// Generate an error message.
+ /// \param state the state where the error occurred.
+ /// \param tok the lookahead token.
+ virtual std::string yysyntax_error_ (int yystate]dnl
+b4_error_verbose_if([, int tok])[);
+
+#if YYDEBUG
+ /// \brief Report a symbol value on the debug stream.
+ /// \param yytype The token type.
+ /// \param yyvaluep Its semantic value.
+ /// \param yylocationp Its location.
+ virtual void yy_symbol_value_print_ (int yytype,
+ const semantic_type* yyvaluep,
+ const location_type* yylocationp);
+ /// \brief Report a symbol on the debug stream.
+ /// \param yytype The token type.
+ /// \param yyvaluep Its semantic value.
+ /// \param yylocationp Its location.
+ virtual void yy_symbol_print_ (int yytype,
+ const semantic_type* yyvaluep,
+ const location_type* yylocationp);
+#endif
+
+
+ /// State numbers.
+ typedef int state_type;
+ /// State stack type.
+ typedef stack<state_type> state_stack_type;
+ /// Semantic value stack type.
+ typedef stack<semantic_type> semantic_stack_type;
+ /// location stack type.
+ typedef stack<location_type> location_stack_type;
+
+ /// The state stack.
+ state_stack_type yystate_stack_;
+ /// The semantic value stack.
+ semantic_stack_type yysemantic_stack_;
+ /// The location stack.
+ location_stack_type yylocation_stack_;
+
+ /// Internal symbol numbers.
+ typedef ]b4_int_type_for([b4_translate])[ token_number_type;
+ /* Tables. */
+ /// For a state, the index in \a yytable_ of its portion.
+ static const ]b4_int_type_for([b4_pact])[ yypact_[];
+ static const ]b4_int_type(b4_pact_ninf, b4_pact_ninf)[ yypact_ninf_;
+
+ /// For a state, default rule to reduce.
+ /// Unless\a yytable_ specifies something else to do.
+ /// Zero means the default is an error.
+ static const ]b4_int_type_for([b4_defact])[ yydefact_[];
+
+ static const ]b4_int_type_for([b4_pgoto])[ yypgoto_[];
+ static const ]b4_int_type_for([b4_defgoto])[ yydefgoto_[];
+
+ /// What to do in a state.
+ /// \a yytable_[yypact_[s]]: what to do in state \a s.
+ /// - if positive, shift that token.
+ /// - if negative, reduce the rule which number is the opposite.
+ /// - if zero, do what YYDEFACT says.
+ static const ]b4_int_type_for([b4_table])[ yytable_[];
+ static const ]b4_int_type(b4_table_ninf, b4_table_ninf)[ yytable_ninf_;
+
+ static const ]b4_int_type_for([b4_check])[ yycheck_[];
+
+ /// For a state, its accessing symbol.
+ static const ]b4_int_type_for([b4_stos])[ yystos_[];
+
+ /// For a rule, its LHS.
+ static const ]b4_int_type_for([b4_r1])[ yyr1_[];
+ /// For a rule, its RHS length.
+ static const ]b4_int_type_for([b4_r2])[ yyr2_[];
+
+#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+ /// For a symbol, its name in clear.
+ static const char* const yytname_[];
+#endif
+
+#if YYERROR_VERBOSE
+ /// Convert the symbol name \a n to a form suitable for a diagnostic.
+ virtual std::string yytnamerr_ (const char *n);
+#endif
+
+#if YYDEBUG
+ /// A type to store symbol numbers and -1.
+ typedef ]b4_int_type_for([b4_rhs])[ rhs_number_type;
+ /// A `-1'-separated list of the rules' RHS.
+ static const rhs_number_type yyrhs_[];
+ /// For each rule, the index of the first RHS symbol in \a yyrhs_.
+ static const ]b4_int_type_for([b4_prhs])[ yyprhs_[];
+ /// For each rule, its source line number.
+ static const ]b4_int_type_for([b4_rline])[ yyrline_[];
+ /// For each scanner token number, its symbol number.
+ static const ]b4_int_type_for([b4_toknum])[ yytoken_number_[];
+ /// Report on the debug stream that the rule \a r is going to be reduced.
+ virtual void yy_reduce_print_ (int r);
+ /// Print the state stack on the debug stream.
+ virtual void yystack_print_ ();
+
+ /* Debugging. */
+ int yydebug_;
+ std::ostream* yycdebug_;
+#endif
+
+ /// Convert a scanner token number \a t to a symbol number.
+ token_number_type yytranslate_ (int t);
+
+ /// \brief Reclaim the memory associated to a symbol.
+ /// \param yymsg Why this token is reclaimed.
+ /// \param yytype The symbol type.
+ /// \param yyvaluep Its semantic value.
+ /// \param yylocationp Its location.
+ inline void yydestruct_ (const char* yymsg,
+ int yytype,
+ semantic_type* yyvaluep,
+ location_type* yylocationp);
+
+ /// Pop \a n symbols the three stacks.
+ inline void yypop_ (unsigned int n = 1);
+
+ /* Constants. */
+ static const int yyeof_;
+ /* LAST_ -- Last index in TABLE_. */
+ static const int yylast_;
+ static const int yynnts_;
+ static const int yyempty_;
+ static const int yyfinal_;
+ static const int yyterror_;
+ static const int yyerrcode_;
+ static const int yyntokens_;
+ static const unsigned int yyuser_token_number_max_;
+ static const token_number_type yyundef_token_;
+]b4_parse_param_vars[
+ };
+]b4_namespace_close[
+
+]b4_percent_define_flag_if([[global_tokens_and_yystype]],
+[b4_token_defines(b4_tokens)
+
+#ifndef YYSTYPE
+ /* Redirection for backward compatibility. */
+# define YYSTYPE b4_namespace_ref::b4_parser_class_name::semantic_type
+#endif
+])
+b4_percent_code_get([[provides]])[]dnl
+
+[#endif /* ! defined PARSER_HEADER_H */]
+])dnl
+@output(b4_parser_file_name@)
+b4_copyright([Skeleton implementation for Bison LALR(1) parsers in C++],
+ [2002, 2003, 2004, 2005, 2006, 2007, 2008])
+b4_percent_code_get([[top]])[]dnl
+m4_if(b4_prefix, [yy], [],
+[
+// Take the name prefix into account.
+#define yylex b4_prefix[]lex])[
+
+/* First part of user declarations. */
+]b4_user_pre_prologue
+
+b4_defines_if([[
+#include "@basename(]b4_spec_defines_file[@)"]])[
+
+/* User implementation prologue. */
+]b4_user_post_prologue
+b4_percent_code_get[]dnl
+
+[#ifndef YY_
+# if YYENABLE_NLS
+# if ENABLE_NLS
+# include <libintl.h> /* FIXME: INFRINGES ON USER NAME SPACE */
+# define YY_(msgid) dgettext ("bison-runtime", msgid)
+# endif
+# endif
+# ifndef YY_
+# define YY_(msgid) msgid
+# endif
+#endif
+
+/* Suppress unused-variable warnings by "using" E. */
+#define YYUSE(e) ((void) (e))
+
+/* Enable debugging if requested. */
+#if YYDEBUG
+
+/* A pseudo ostream that takes yydebug_ into account. */
+# define YYCDEBUG if (yydebug_) (*yycdebug_)
+
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
+do { \
+ if (yydebug_) \
+ { \
+ *yycdebug_ << Title << ' '; \
+ yy_symbol_print_ ((Type), (Value), (Location)); \
+ *yycdebug_ << std::endl; \
+ } \
+} while (false)
+
+# define YY_REDUCE_PRINT(Rule) \
+do { \
+ if (yydebug_) \
+ yy_reduce_print_ (Rule); \
+} while (false)
+
+# define YY_STACK_PRINT() \
+do { \
+ if (yydebug_) \
+ yystack_print_ (); \
+} while (false)
+
+#else /* !YYDEBUG */
+
+# define YYCDEBUG if (false) std::cerr
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
+# define YY_REDUCE_PRINT(Rule)
+# define YY_STACK_PRINT()
+
+#endif /* !YYDEBUG */
+
+#define yyerrok (yyerrstatus_ = 0)
+#define yyclearin (yychar = yyempty_)
+
+#define YYACCEPT goto yyacceptlab
+#define YYABORT goto yyabortlab
+#define YYERROR goto yyerrorlab
+#define YYRECOVERING() (!!yyerrstatus_)
+
+]b4_namespace_open[
+#if YYERROR_VERBOSE
+
+ /* Return YYSTR after stripping away unnecessary quotes and
+ backslashes, so that it's suitable for yyerror. The heuristic is
+ that double-quoting is unnecessary unless the string contains an
+ apostrophe, a comma, or backslash (other than backslash-backslash).
+ YYSTR is taken from yytname. */
+ std::string
+ ]b4_parser_class_name[::yytnamerr_ (const char *yystr)
+ {
+ if (*yystr == '"')
+ {
+ std::string yyr = "";
+ char const *yyp = yystr;
+
+ for (;;)
+ switch (*++yyp)
+ {
+ case '\'':
+ case ',':
+ goto do_not_strip_quotes;
+
+ case '\\':
+ if (*++yyp != '\\')
+ goto do_not_strip_quotes;
+ /* Fall through. */
+ default:
+ yyr += *yyp;
+ break;
+
+ case '"':
+ return yyr;
+ }
+ do_not_strip_quotes: ;
+ }
+
+ return yystr;
+ }
+
+#endif
+
+ /// Build a parser object.
+ ]b4_parser_class_name::b4_parser_class_name[ (]b4_parse_param_decl[ ]b4_parser_class_constructor_param[) ]b4_parser_class_constructor_init[ ]m4_ifset([b4_parse_param], [
+ :])[
+
+#if YYDEBUG
+ ]m4_ifset([b4_parse_param], [ ], [ :])[yydebug_ (false),
+ yycdebug_ (&std::cerr)]m4_ifset([b4_parse_param], [,])[
+#endif]b4_parse_param_cons[
+ {
+ }
+
+ ]b4_parser_class_name::~b4_parser_class_name[ ()
+ {
+ }
+
+#if YYDEBUG
+ /*--------------------------------.
+ | Print this symbol on YYOUTPUT. |
+ `--------------------------------*/
+
+ inline void
+ ]b4_parser_class_name[::yy_symbol_value_print_ (int yytype,
+ const semantic_type* yyvaluep, const location_type* yylocationp)
+ {
+ YYUSE (yylocationp);
+ YYUSE (yyvaluep);
+ switch (yytype)
+ {
+ ]m4_map([b4_symbol_actions], m4_defn([b4_symbol_printers]))dnl
+[ default:
+ break;
+ }
+ }
+
+
+ void
+ ]b4_parser_class_name[::yy_symbol_print_ (int yytype,
+ const semantic_type* yyvaluep, const location_type* yylocationp)
+ {
+ *yycdebug_ << (yytype < yyntokens_ ? "token" : "nterm")
+ << ' ' << yytname_[yytype] << " ("
+ << *yylocationp << ": ";
+ yy_symbol_value_print_ (yytype, yyvaluep, yylocationp);
+ *yycdebug_ << ')';
+ }
+#endif
+
+ void
+ ]b4_parser_class_name[::yydestruct_ (const char* yymsg,
+ int yytype, semantic_type* yyvaluep, location_type* yylocationp)
+ {
+ YYUSE (yylocationp);
+ YYUSE (yymsg);
+ YYUSE (yyvaluep);
+
+ YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
+
+]m4_ifset([b4_symbol_actions], [ ], [
+ switch (yytype)
+ {
+ ]m4_map([b4_symbol_actions], m4_defn([b4_symbol_destructors]))[
+ default:
+ break;
+ }
+ ])[
+ }
+
+ void
+ ]b4_parser_class_name[::yypop_ (unsigned int n)
+ {
+ yystate_stack_.pop (n);
+ yysemantic_stack_.pop (n);
+ yylocation_stack_.pop (n);
+ }
+
+#if YYDEBUG
+ std::ostream&
+ ]b4_parser_class_name[::debug_stream () const
+ {
+ return *yycdebug_;
+ }
+
+ void
+ ]b4_parser_class_name[::set_debug_stream (std::ostream& o)
+ {
+ yycdebug_ = &o;
+ }
+
+
+ ]b4_parser_class_name[::debug_level_type
+ ]b4_parser_class_name[::debug_level () const
+ {
+ return yydebug_;
+ }
+
+ void
+ ]b4_parser_class_name[::set_debug_level (debug_level_type l)
+ {
+ yydebug_ = l;
+ }
+#endif
+
+ int
+ ]b4_parser_class_name[::parse ()
+ {
+ /// Lookahead and lookahead in internal form.
+ int yychar = yyempty_;
+ int yytoken = 0;
+
+ /* State. */
+ int yyn;
+ int yylen = 0;
+ int yystate = 0;
+
+ /* Error handling. */
+ int yynerrs_ = 0;
+ int yyerrstatus_ = 0;
+
+ /// Semantic value of the lookahead.
+ semantic_type yylval;
+ /// Location of the lookahead.
+ location_type yylloc;
+ /// The locations where the error started and ended.
+ location_type yyerror_range[2];
+
+ /// $$.
+ semantic_type yyval;
+ /// @@$.
+ location_type yyloc;
+
+ int yyresult;
+
+ YYCDEBUG << "Starting parse" << std::endl;
+
+]m4_ifdef([b4_initial_action], [
+m4_pushdef([b4_at_dollar], [yylloc])dnl
+m4_pushdef([b4_dollar_dollar], [yylval])dnl
+ /* User initialization code. */
+ b4_user_initial_action
+m4_popdef([b4_dollar_dollar])dnl
+m4_popdef([b4_at_dollar])])dnl
+
+ [ /* Initialize the stacks. The initial state will be pushed in
+ yynewstate, since the latter expects the semantical and the
+ location values to have been already stored, initialize these
+ stacks with a primary value. */
+ yystate_stack_ = state_stack_type (0);
+ yysemantic_stack_ = semantic_stack_type (0);
+ yylocation_stack_ = location_stack_type (0);
+ yysemantic_stack_.push (yylval);
+ yylocation_stack_.push (yylloc);
+
+ /* New state. */
+ yynewstate:
+ yystate_stack_.push (yystate);
+ YYCDEBUG << "Entering state " << yystate << std::endl;
+
+ /* Accept? */
+ if (yystate == yyfinal_)
+ goto yyacceptlab;
+
+ goto yybackup;
+
+ /* Backup. */
+ yybackup:
+
+ /* Try to take a decision without lookahead. */
+ yyn = yypact_[yystate];
+ if (yyn == yypact_ninf_)
+ goto yydefault;
+
+ /* Read a lookahead token. */
+ if (yychar == yyempty_)
+ {
+ YYCDEBUG << "Reading a token: ";
+ yychar = ]b4_c_function_call([yylex], [int],
+ [[YYSTYPE*], [&yylval]][]dnl
+b4_locations_if([, [[location*], [&yylloc]]])dnl
+m4_ifdef([b4_lex_param], [, ]b4_lex_param))[;
+ }
+
+
+ /* Convert token to internal form. */
+ if (yychar <= yyeof_)
+ {
+ yychar = yytoken = yyeof_;
+ YYCDEBUG << "Now at end of input." << std::endl;
+ }
+ else
+ {
+ yytoken = yytranslate_ (yychar);
+ YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
+ }
+
+ /* If the proper action on seeing token YYTOKEN is to reduce or to
+ detect an error, take that action. */
+ yyn += yytoken;
+ if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yytoken)
+ goto yydefault;
+
+ /* Reduce or error. */
+ yyn = yytable_[yyn];
+ if (yyn <= 0)
+ {
+ if (yyn == 0 || yyn == yytable_ninf_)
+ goto yyerrlab;
+ yyn = -yyn;
+ goto yyreduce;
+ }
+
+ /* Shift the lookahead token. */
+ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
+
+ /* Discard the token being shifted. */
+ yychar = yyempty_;
+
+ yysemantic_stack_.push (yylval);
+ yylocation_stack_.push (yylloc);
+
+ /* Count tokens shifted since error; after three, turn off error
+ status. */
+ if (yyerrstatus_)
+ --yyerrstatus_;
+
+ yystate = yyn;
+ goto yynewstate;
+
+ /*-----------------------------------------------------------.
+ | yydefault -- do the default action for the current state. |
+ `-----------------------------------------------------------*/
+ yydefault:
+ yyn = yydefact_[yystate];
+ if (yyn == 0)
+ goto yyerrlab;
+ goto yyreduce;
+
+ /*-----------------------------.
+ | yyreduce -- Do a reduction. |
+ `-----------------------------*/
+ yyreduce:
+ yylen = yyr2_[yyn];
+ /* If YYLEN is nonzero, implement the default value of the action:
+ `$$ = $1'. Otherwise, use the top of the stack.
+
+ Otherwise, the following line sets YYVAL to garbage.
+ This behavior is undocumented and Bison
+ users should not rely upon it. */
+ if (yylen)
+ yyval = yysemantic_stack_[yylen - 1];
+ else
+ yyval = yysemantic_stack_[0];
+
+ {
+ slice<location_type, location_stack_type> slice (yylocation_stack_, yylen);
+ YYLLOC_DEFAULT (yyloc, slice, yylen);
+ }
+ YY_REDUCE_PRINT (yyn);
+ switch (yyn)
+ {
+ ]b4_user_actions[
+ default:
+ break;
+ }
+ YY_SYMBOL_PRINT ("-> $$ =", yyr1_[yyn], &yyval, &yyloc);
+
+ yypop_ (yylen);
+ yylen = 0;
+ YY_STACK_PRINT ();
+
+ yysemantic_stack_.push (yyval);
+ yylocation_stack_.push (yyloc);
+
+ /* Shift the result of the reduction. */
+ yyn = yyr1_[yyn];
+ yystate = yypgoto_[yyn - yyntokens_] + yystate_stack_[0];
+ if (0 <= yystate && yystate <= yylast_
+ && yycheck_[yystate] == yystate_stack_[0])
+ yystate = yytable_[yystate];
+ else
+ yystate = yydefgoto_[yyn - yyntokens_];
+ goto yynewstate;
+
+ /*------------------------------------.
+ | yyerrlab -- here on detecting error |
+ `------------------------------------*/
+ yyerrlab:
+ /* If not already recovering from an error, report this error. */
+ if (!yyerrstatus_)
+ {
+ ++yynerrs_;
+ error (yylloc, yysyntax_error_ (yystate]dnl
+b4_error_verbose_if([, yytoken])[));
+ }
+
+ yyerror_range[0] = yylloc;
+ if (yyerrstatus_ == 3)
+ {
+ /* If just tried and failed to reuse lookahead token after an
+ error, discard it. */
+
+ if (yychar <= yyeof_)
+ {
+ /* Return failure if at end of input. */
+ if (yychar == yyeof_)
+ YYABORT;
+ }
+ else
+ {
+ yydestruct_ ("Error: discarding", yytoken, &yylval, &yylloc);
+ yychar = yyempty_;
+ }
+ }
+
+ /* Else will try to reuse lookahead token after shifting the error
+ token. */
+ goto yyerrlab1;
+
+
+ /*---------------------------------------------------.
+ | yyerrorlab -- error raised explicitly by YYERROR. |
+ `---------------------------------------------------*/
+ yyerrorlab:
+
+ /* Pacify compilers like GCC when the user code never invokes
+ YYERROR and the label yyerrorlab therefore never appears in user
+ code. */
+ if (false)
+ goto yyerrorlab;
+
+ yyerror_range[0] = yylocation_stack_[yylen - 1];
+ /* Do not reclaim the symbols of the rule which action triggered
+ this YYERROR. */
+ yypop_ (yylen);
+ yylen = 0;
+ yystate = yystate_stack_[0];
+ goto yyerrlab1;
+
+ /*-------------------------------------------------------------.
+ | yyerrlab1 -- common code for both syntax error and YYERROR. |
+ `-------------------------------------------------------------*/
+ yyerrlab1:
+ yyerrstatus_ = 3; /* Each real token shifted decrements this. */
+
+ for (;;)
+ {
+ yyn = yypact_[yystate];
+ if (yyn != yypact_ninf_)
+ {
+ yyn += yyterror_;
+ if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_)
+ {
+ yyn = yytable_[yyn];
+ if (0 < yyn)
+ break;
+ }
+ }
+
+ /* Pop the current state because it cannot handle the error token. */
+ if (yystate_stack_.height () == 1)
+ YYABORT;
+
+ yyerror_range[0] = yylocation_stack_[0];
+ yydestruct_ ("Error: popping",
+ yystos_[yystate],
+ &yysemantic_stack_[0], &yylocation_stack_[0]);
+ yypop_ ();
+ yystate = yystate_stack_[0];
+ YY_STACK_PRINT ();
+ }
+
+ yyerror_range[1] = yylloc;
+ // Using YYLLOC is tempting, but would change the location of
+ // the lookahead. YYLOC is available though.
+ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2);
+ yysemantic_stack_.push (yylval);
+ yylocation_stack_.push (yyloc);
+
+ /* Shift the error token. */
+ YY_SYMBOL_PRINT ("Shifting", yystos_[yyn],
+ &yysemantic_stack_[0], &yylocation_stack_[0]);
+
+ yystate = yyn;
+ goto yynewstate;
+
+ /* Accept. */
+ yyacceptlab:
+ yyresult = 0;
+ goto yyreturn;
+
+ /* Abort. */
+ yyabortlab:
+ yyresult = 1;
+ goto yyreturn;
+
+ yyreturn:
+ if (yychar != yyempty_)
+ yydestruct_ ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc);
+
+ /* Do not reclaim the symbols of the rule which action triggered
+ this YYABORT or YYACCEPT. */
+ yypop_ (yylen);
+ while (yystate_stack_.height () != 1)
+ {
+ yydestruct_ ("Cleanup: popping",
+ yystos_[yystate_stack_[0]],
+ &yysemantic_stack_[0],
+ &yylocation_stack_[0]);
+ yypop_ ();
+ }
+
+ return yyresult;
+ }
+
+ // Generate an error message.
+ std::string
+ ]b4_parser_class_name[::yysyntax_error_ (int yystate]dnl
+b4_error_verbose_if([, int tok])[)
+ {
+ std::string res;
+ YYUSE (yystate);
+#if YYERROR_VERBOSE
+ int yyn = yypact_[yystate];
+ if (yypact_ninf_ < yyn && yyn <= yylast_)
+ {
+ /* Start YYX at -YYN if negative to avoid negative indexes in
+ YYCHECK. */
+ int yyxbegin = yyn < 0 ? -yyn : 0;
+
+ /* Stay within bounds of both yycheck and yytname. */
+ int yychecklim = yylast_ - yyn + 1;
+ int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_;
+ int count = 0;
+ for (int x = yyxbegin; x < yyxend; ++x)
+ if (yycheck_[x + yyn] == x && x != yyterror_)
+ ++count;
+
+ // FIXME: This method of building the message is not compatible
+ // with internationalization. It should work like yacc.c does it.
+ // That is, first build a string that looks like this:
+ // "syntax error, unexpected %s or %s or %s"
+ // Then, invoke YY_ on this string.
+ // Finally, use the string as a format to output
+ // yytname_[tok], etc.
+ // Until this gets fixed, this message appears in English only.
+ res = "syntax error, unexpected ";
+ res += yytnamerr_ (yytname_[tok]);
+ if (count < 5)
+ {
+ count = 0;
+ for (int x = yyxbegin; x < yyxend; ++x)
+ if (yycheck_[x + yyn] == x && x != yyterror_)
+ {
+ res += (!count++) ? ", expecting " : " or ";
+ res += yytnamerr_ (yytname_[x]);
+ }
+ }
+ }
+ else
+#endif
+ res = YY_("syntax error");
+ return res;
+ }
+
+
+ /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+ STATE-NUM. */
+ const ]b4_int_type(b4_pact_ninf, b4_pact_ninf) b4_parser_class_name::yypact_ninf_ = b4_pact_ninf[;
+ const ]b4_int_type_for([b4_pact])[
+ ]b4_parser_class_name[::yypact_[] =
+ {
+ ]b4_pact[
+ };
+
+ /* YYDEFACT[S] -- default rule to reduce with in state S when YYTABLE
+ doesn't specify something else to do. Zero means the default is an
+ error. */
+ const ]b4_int_type_for([b4_defact])[
+ ]b4_parser_class_name[::yydefact_[] =
+ {
+ ]b4_defact[
+ };
+
+ /* YYPGOTO[NTERM-NUM]. */
+ const ]b4_int_type_for([b4_pgoto])[
+ ]b4_parser_class_name[::yypgoto_[] =
+ {
+ ]b4_pgoto[
+ };
+
+ /* YYDEFGOTO[NTERM-NUM]. */
+ const ]b4_int_type_for([b4_defgoto])[
+ ]b4_parser_class_name[::yydefgoto_[] =
+ {
+ ]b4_defgoto[
+ };
+
+ /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
+ positive, shift that token. If negative, reduce the rule which
+ number is the opposite. If zero, do what YYDEFACT says. */
+ const ]b4_int_type(b4_table_ninf, b4_table_ninf) b4_parser_class_name::yytable_ninf_ = b4_table_ninf[;
+ const ]b4_int_type_for([b4_table])[
+ ]b4_parser_class_name[::yytable_[] =
+ {
+ ]b4_table[
+ };
+
+ /* YYCHECK. */
+ const ]b4_int_type_for([b4_check])[
+ ]b4_parser_class_name[::yycheck_[] =
+ {
+ ]b4_check[
+ };
+
+ /* STOS_[STATE-NUM] -- The (internal number of the) accessing
+ symbol of state STATE-NUM. */
+ const ]b4_int_type_for([b4_stos])[
+ ]b4_parser_class_name[::yystos_[] =
+ {
+ ]b4_stos[
+ };
+
+#if YYDEBUG
+ /* TOKEN_NUMBER_[YYLEX-NUM] -- Internal symbol number corresponding
+ to YYLEX-NUM. */
+ const ]b4_int_type_for([b4_toknum])[
+ ]b4_parser_class_name[::yytoken_number_[] =
+ {
+ ]b4_toknum[
+ };
+#endif
+
+ /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
+ const ]b4_int_type_for([b4_r1])[
+ ]b4_parser_class_name[::yyr1_[] =
+ {
+ ]b4_r1[
+ };
+
+ /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
+ const ]b4_int_type_for([b4_r2])[
+ ]b4_parser_class_name[::yyr2_[] =
+ {
+ ]b4_r2[
+ };
+
+#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+ /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
+ First, the terminals, then, starting at \a yyntokens_, nonterminals. */
+ const char*
+ const ]b4_parser_class_name[::yytname_[] =
+ {
+ ]b4_tname[
+ };
+#endif
+
+#if YYDEBUG
+ /* YYRHS -- A `-1'-separated list of the rules' RHS. */
+ const ]b4_parser_class_name[::rhs_number_type
+ ]b4_parser_class_name[::yyrhs_[] =
+ {
+ ]b4_rhs[
+ };
+
+ /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
+ YYRHS. */
+ const ]b4_int_type_for([b4_prhs])[
+ ]b4_parser_class_name[::yyprhs_[] =
+ {
+ ]b4_prhs[
+ };
+
+ /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
+ const ]b4_int_type_for([b4_rline])[
+ ]b4_parser_class_name[::yyrline_[] =
+ {
+ ]b4_rline[
+ };
+
+ // Print the state stack on the debug stream.
+ void
+ ]b4_parser_class_name[::yystack_print_ ()
+ {
+ *yycdebug_ << "Stack now";
+ for (state_stack_type::const_iterator i = yystate_stack_.begin ();
+ i != yystate_stack_.end (); ++i)
+ *yycdebug_ << ' ' << *i;
+ *yycdebug_ << std::endl;
+ }
+
+ // Report on the debug stream that the rule \a yyrule is going to be reduced.
+ void
+ ]b4_parser_class_name[::yy_reduce_print_ (int yyrule)
+ {
+ unsigned int yylno = yyrline_[yyrule];
+ int yynrhs = yyr2_[yyrule];
+ /* Print the symbols being reduced, and their result. */
+ *yycdebug_ << "Reducing stack by rule " << yyrule - 1
+ << " (line " << yylno << "):" << std::endl;
+ /* The symbols being reduced. */
+ for (int yyi = 0; yyi < yynrhs; yyi++)
+ YY_SYMBOL_PRINT (" $" << yyi + 1 << " =",
+ yyrhs_[yyprhs_[yyrule] + yyi],
+ &]b4_rhs_value(yynrhs, yyi + 1)[,
+ &]b4_rhs_location(yynrhs, yyi + 1)[);
+ }
+#endif // YYDEBUG
+
+ /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
+ ]b4_parser_class_name[::token_number_type
+ ]b4_parser_class_name[::yytranslate_ (int t)
+ {
+ static
+ const token_number_type
+ translate_table[] =
+ {
+ ]b4_translate[
+ };
+ if ((unsigned int) t <= yyuser_token_number_max_)
+ return translate_table[t];
+ else
+ return yyundef_token_;
+ }
+
+ const int ]b4_parser_class_name[::yyeof_ = 0;
+ const int ]b4_parser_class_name[::yylast_ = ]b4_last[;
+ const int ]b4_parser_class_name[::yynnts_ = ]b4_nterms_number[;
+ const int ]b4_parser_class_name[::yyempty_ = -2;
+ const int ]b4_parser_class_name[::yyfinal_ = ]b4_final_state_number[;
+ const int ]b4_parser_class_name[::yyterror_ = 1;
+ const int ]b4_parser_class_name[::yyerrcode_ = 256;
+ const int ]b4_parser_class_name[::yyntokens_ = ]b4_tokens_number[;
+
+ const unsigned int ]b4_parser_class_name[::yyuser_token_number_max_ = ]b4_user_token_number_max[;
+ const ]b4_parser_class_name[::token_number_type ]b4_parser_class_name[::yyundef_token_ = ]b4_undef_token_number[;
+
+]b4_namespace_close[
+
+]b4_epilogue
+dnl
+@output(b4_dir_prefix[]stack.hh@)
+b4_copyright([Stack handling for Bison parsers in C++],
+ [2002, 2003, 2004, 2005, 2006, 2007, 2008])[
+
+#ifndef BISON_STACK_HH
+# define BISON_STACK_HH
+
+#include <deque>
+
+]b4_namespace_open[
+ template <class T, class S = std::deque<T> >
+ class stack
+ {
+ public:
+
+ // Hide our reversed order.
+ typedef typename S::reverse_iterator iterator;
+ typedef typename S::const_reverse_iterator const_iterator;
+
+ stack () : seq_ ()
+ {
+ }
+
+ stack (unsigned int n) : seq_ (n)
+ {
+ }
+
+ inline
+ T&
+ operator [] (unsigned int i)
+ {
+ return seq_[i];
+ }
+
+ inline
+ const T&
+ operator [] (unsigned int i) const
+ {
+ return seq_[i];
+ }
+
+ inline
+ void
+ push (const T& t)
+ {
+ seq_.push_front (t);
+ }
+
+ inline
+ void
+ pop (unsigned int n = 1)
+ {
+ for (; n; --n)
+ seq_.pop_front ();
+ }
+
+ inline
+ unsigned int
+ height () const
+ {
+ return seq_.size ();
+ }
+
+ inline const_iterator begin () const { return seq_.rbegin (); }
+ inline const_iterator end () const { return seq_.rend (); }
+
+ private:
+
+ S seq_;
+ };
+
+ /// Present a slice of the top of a stack.
+ template <class T, class S = stack<T> >
+ class slice
+ {
+ public:
+
+ slice (const S& stack,
+ unsigned int range) : stack_ (stack),
+ range_ (range)
+ {
+ }
+
+ inline
+ const T&
+ operator [] (unsigned int i) const
+ {
+ return stack_[range_ - i];
+ }
+
+ private:
+
+ const S& stack_;
+ unsigned int range_;
+ };
+]b4_namespace_close[
+
+#endif // not BISON_STACK_HH[]dnl
+]
+m4_divert_pop(0)
diff --git a/tools/mhmake/src/bisondata/location.cc b/tools/mhmake/src/bisondata/location.cc
new file mode 100644
index 000000000..e142e5115
--- /dev/null
+++ b/tools/mhmake/src/bisondata/location.cc
@@ -0,0 +1,279 @@
+# C++ skeleton for Bison
+
+# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation,
+# Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# We do want M4 expansion after # for CPP macros.
+m4_changecom()
+m4_divert_push(0)dnl
+@output(b4_dir_prefix[]position.hh@)
+b4_copyright([Positions for Bison parsers in C++],
+ [2002, 2003, 2004, 2005, 2006])[
+
+/**
+ ** \file position.hh
+ ** Define the ]b4_namespace_ref[::position class.
+ */
+
+#ifndef BISON_POSITION_HH
+# define BISON_POSITION_HH
+
+# include <iostream>
+# include <string>
+# include <algorithm>
+
+]b4_namespace_open[
+ /// Abstract a position.
+ class position
+ {
+ public:
+]m4_ifdef([b4_location_constructors], [
+ /// Construct a position.
+ position ()
+ : filename (0), line (]b4_location_initial_line[), column (]b4_location_initial_column[)
+ {
+ }
+
+])[
+ /// Initialization.
+ inline void initialize (]b4_percent_define_get([[filename_type]])[* fn)
+ {
+ filename = fn;
+ line = ]b4_location_initial_line[;
+ column = ]b4_location_initial_column[;
+ }
+
+ /** \name Line and Column related manipulators
+ ** \{ */
+ public:
+ /// (line related) Advance to the COUNT next lines.
+ inline void lines (int count = 1)
+ {
+ column = ]b4_location_initial_column[;
+ line += count;
+ }
+ /// (column related) Advance to the COUNT next columns.
+ inline void columns (int count = 1)
+ {
+ column = std::max (]b4_location_initial_column[u, column + count);
+ }
+ /** \} */
+
+ public:
+ /// File name to which this position refers.
+ ]b4_percent_define_get([[filename_type]])[* filename;
+ /// Current line number.
+ unsigned int line;
+ /// Current column number.
+ unsigned int column;
+ };
+
+ /// Add and assign a position.
+ inline const position&
+ operator+= (position& res, const int width)
+ {
+ res.columns (width);
+ return res;
+ }
+
+ /// Add two position objects.
+ inline const position
+ operator+ (const position& begin, const int width)
+ {
+ position res = begin;
+ return res += width;
+ }
+
+ /// Add and assign a position.
+ inline const position&
+ operator-= (position& res, const int width)
+ {
+ return res += -width;
+ }
+
+ /// Add two position objects.
+ inline const position
+ operator- (const position& begin, const int width)
+ {
+ return begin + -width;
+ }
+]b4_percent_define_flag_if([[define_location_comparison]], [[
+ /// Compare two position objects.
+ inline bool
+ operator== (const position& pos1, const position& pos2)
+ {
+ return
+ (pos1.filename == pos2.filename
+ || pos1.filename && pos2.filename && *pos1.filename == *pos2.filename)
+ && pos1.line == pos2.line && pos1.column == pos2.column;
+ }
+
+ /// Compare two position objects.
+ inline bool
+ operator!= (const position& pos1, const position& pos2)
+ {
+ return !(pos1 == pos2);
+ }
+]])[
+ /** \brief Intercept output stream redirection.
+ ** \param ostr the destination output stream
+ ** \param pos a reference to the position to redirect
+ */
+ inline std::ostream&
+ operator<< (std::ostream& ostr, const position& pos)
+ {
+ if (pos.filename)
+ ostr << *pos.filename << ':';
+ return ostr << pos.line << '.' << pos.column;
+ }
+
+]b4_namespace_close[
+#endif // not BISON_POSITION_HH]
+@output(b4_dir_prefix[]location.hh@)
+b4_copyright([Locations for Bison parsers in C++],
+ [2002, 2003, 2004, 2005, 2006])[
+
+/**
+ ** \file location.hh
+ ** Define the ]b4_namespace_ref[::location class.
+ */
+
+#ifndef BISON_LOCATION_HH
+# define BISON_LOCATION_HH
+
+# include <iostream>
+# include <string>
+# include "position.hh"
+
+]b4_namespace_open[
+
+ /// Abstract a location.
+ class location
+ {
+ public:
+]m4_ifdef([b4_location_constructors], [
+ /// Construct a location.
+ location ()
+ : begin (), end ()
+ {
+ }
+
+])[
+ /// Initialization.
+ inline void initialize (]b4_percent_define_get([[filename_type]])[* fn)
+ {
+ begin.initialize (fn);
+ end = begin;
+ }
+
+ /** \name Line and Column related manipulators
+ ** \{ */
+ public:
+ /// Reset initial location to final location.
+ inline void step ()
+ {
+ begin = end;
+ }
+
+ /// Extend the current location to the COUNT next columns.
+ inline void columns (unsigned int count = 1)
+ {
+ end += count;
+ }
+
+ /// Extend the current location to the COUNT next lines.
+ inline void lines (unsigned int count = 1)
+ {
+ end.lines (count);
+ }
+ inline void incline ()
+ {
+ lines(1);
+ step();
+ }
+ /** \} */
+
+
+ public:
+ /// Beginning of the located region.
+ position begin;
+ /// End of the located region.
+ position end;
+ };
+
+ /// Join two location objects to create a location.
+ inline const location operator+ (const location& begin, const location& end)
+ {
+ location res = begin;
+ res.end = end.end;
+ return res;
+ }
+
+ /// Add two location objects.
+ inline const location operator+ (const location& begin, unsigned int width)
+ {
+ location res = begin;
+ res.columns (width);
+ return res;
+ }
+
+ /// Add and assign a location.
+ inline location& operator+= (location& res, unsigned int width)
+ {
+ res.columns (width);
+ return res;
+ }
+]b4_percent_define_flag_if([[define_location_comparison]], [[
+ /// Compare two location objects.
+ inline bool
+ operator== (const location& loc1, const location& loc2)
+ {
+ return loc1.begin == loc2.begin && loc1.end == loc2.end;
+ }
+
+ /// Compare two location objects.
+ inline bool
+ operator!= (const location& loc1, const location& loc2)
+ {
+ return !(loc1 == loc2);
+ }
+]])[
+ /** \brief Intercept output stream redirection.
+ ** \param ostr the destination output stream
+ ** \param loc a reference to the location to redirect
+ **
+ ** Avoid duplicate information.
+ */
+ inline std::ostream& operator<< (std::ostream& ostr, const location& loc)
+ {
+ position last = loc.end - 1;
+ ostr << loc.begin;
+ if (last.filename
+ && (!loc.begin.filename
+ || *loc.begin.filename != *last.filename))
+ ostr << '-' << last;
+ else if (loc.begin.line != last.line)
+ ostr << '-' << last.line << '.' << last.column;
+ else if (loc.begin.column != last.column)
+ ostr << '-' << last.column;
+ return ostr;
+ }
+
+]b4_namespace_close[
+
+#endif // not BISON_LOCATION_HH]
+m4_divert_pop(0)
+m4_changecom([#])
diff --git a/tools/mhmake/src/bisondata/m4sugar/foreach.m4 b/tools/mhmake/src/bisondata/m4sugar/foreach.m4
new file mode 100644
index 000000000..f6b724d77
--- /dev/null
+++ b/tools/mhmake/src/bisondata/m4sugar/foreach.m4
@@ -0,0 +1,400 @@
+# -*- Autoconf -*-
+# This file is part of Autoconf.
+# foreach-based replacements for recursive functions.
+# Speeds up GNU M4 1.4.x by avoiding quadratic $@ recursion, but penalizes
+# GNU M4 1.6 by requiring more memory and macro expansions.
+#
+# Copyright (C) 2008 Free Software Foundation, Inc.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# As a special exception, the Free Software Foundation gives unlimited
+# permission to copy, distribute and modify the configure scripts that
+# are the output of Autoconf. You need not follow the terms of the GNU
+# General Public License when using or distributing such scripts, even
+# though portions of the text of Autoconf appear in them. The GNU
+# General Public License (GPL) does govern all other use of the material
+# that constitutes the Autoconf program.
+#
+# Certain portions of the Autoconf source text are designed to be copied
+# (in certain cases, depending on the input) into the output of
+# Autoconf. We call these the "data" portions. The rest of the Autoconf
+# source text consists of comments plus executable code that decides which
+# of the data portions to output in any given case. We call these
+# comments and executable code the "non-data" portions. Autoconf never
+# copies any of the non-data portions into its output.
+#
+# This special exception to the GPL applies to versions of Autoconf
+# released by the Free Software Foundation. When you make and
+# distribute a modified version of Autoconf, you may extend this special
+# exception to the GPL to apply to your modified version as well, *unless*
+# your modified version has the potential to copy into its output some
+# of the text that was the non-data portion of the version that you started
+# with. (In other words, unless your change moves or copies text from
+# the non-data portions to the data portions.) If your modification has
+# such potential, you must delete any notice of this special exception
+# to the GPL from your modified version.
+#
+# Written by Eric Blake.
+#
+
+# In M4 1.4.x, every byte of $@ is rescanned. This means that an
+# algorithm on n arguments that recurses with one less argument each
+# iteration will scan n * (n + 1) / 2 arguments, for O(n^2) time. In
+# M4 1.6, this was fixed so that $@ is only scanned once, then
+# back-references are made to information stored about the scan.
+# Thus, n iterations need only scan n arguments, for O(n) time.
+# Additionally, in M4 1.4.x, recursive algorithms did not clean up
+# memory very well, requiring O(n^2) memory rather than O(n) for n
+# iterations.
+#
+# This file is designed to overcome the quadratic nature of $@
+# recursion by writing a variant of m4_foreach that uses m4_for rather
+# than $@ recursion to operate on the list. This involves more macro
+# expansions, but avoids the need to rescan a quadratic number of
+# arguments, making these replacements very attractive for M4 1.4.x.
+# On the other hand, in any version of M4, expanding additional macros
+# costs additional time; therefore, in M4 1.6, where $@ recursion uses
+# fewer macros, these replacements actually pessimize performance.
+# Additionally, the use of $10 to mean the tenth argument violates
+# POSIX; although all versions of m4 1.4.x support this meaning, a
+# future m4 version may switch to take it as the first argument
+# concatenated with a literal 0, so the implementations in this file
+# are not future-proof. Thus, this file is conditionally included as
+# part of m4_init(), only when it is detected that M4 probably has
+# quadratic behavior (ie. it lacks the macro __m4_version__).
+#
+# Please keep this file in sync with m4sugar.m4.
+
+# m4_foreach(VARIABLE, LIST, EXPRESSION)
+# --------------------------------------
+# Expand EXPRESSION assigning each value of the LIST to VARIABLE.
+# LIST should have the form `item_1, item_2, ..., item_n', i.e. the
+# whole list must *quoted*. Quote members too if you don't want them
+# to be expanded.
+#
+# This version minimizes the number of times that $@ is evaluated by
+# using m4_for to generate a boilerplate into VARIABLE then passing $@
+# to that temporary macro. Thus, the recursion is done in m4_for
+# without reparsing any user input, and is not quadratic. For an idea
+# of how this works, note that m4_foreach(i,[1,2],[i]) defines i to be
+# m4_define([$1],[$3])$2[]m4_define([$1],[$4])$2[]m4_popdef([i])
+# then calls i([i],[i],[1],[2]).
+m4_define([m4_foreach],
+[m4_if([$2], [], [], [_$0([$1], [$3], $2)])])
+
+m4_define([_m4_foreach],
+[m4_define([$1], m4_pushdef([$1])_m4_for([$1], [3], [$#], [1],
+ [$0_([1], [2], _m4_defn([$1]))])[m4_popdef([$1])])m4_indir([$1], $@)])
+
+m4_define([_m4_foreach_],
+[[m4_define([$$1], [$$3])$$2[]]])
+
+# m4_case(SWITCH, VAL1, IF-VAL1, VAL2, IF-VAL2, ..., DEFAULT)
+# -----------------------------------------------------------
+# Find the first VAL that SWITCH matches, and expand the corresponding
+# IF-VAL. If there are no matches, expand DEFAULT.
+#
+# Use m4_for to create a temporary macro in terms of a boilerplate
+# m4_if with final cleanup. If $# is even, we have DEFAULT; if it is
+# odd, then rounding the last $# up in the temporary macro is
+# harmless. For example, both m4_case(1,2,3,4,5) and
+# m4_case(1,2,3,4,5,6) result in the intermediate _m4_case being
+# m4_if([$1],[$2],[$3],[$1],[$4],[$5],_m4_popdef([_m4_case])[$6])
+m4_define([m4_case],
+[m4_if(m4_eval([$# <= 2]), [1], [$2],
+[m4_pushdef([_$0], [m4_if(]m4_for([_m4_count], [2], m4_decr([$#]), [2],
+ [_$0_([1], _m4_count, m4_incr(_m4_count))])[_m4_popdef(
+ [_$0])]m4_dquote($m4_eval([($# + 1) & ~1]))[)])_$0($@)])])
+
+m4_define([_m4_case_],
+[[[$$1],[$$2],[$$3],]])
+
+# m4_bmatch(SWITCH, RE1, VAL1, RE2, VAL2, ..., DEFAULT)
+# -----------------------------------------------------
+# m4 equivalent of
+#
+# if (SWITCH =~ RE1)
+# VAL1;
+# elif (SWITCH =~ RE2)
+# VAL2;
+# elif ...
+# ...
+# else
+# DEFAULT
+#
+# We build the temporary macro _m4_b:
+# m4_define([_m4_b], _m4_defn([_m4_bmatch]))_m4_b([$1], [$2], [$3])...
+# _m4_b([$1], [$m-1], [$m])_m4_b([], [], [$m+1]_m4_popdef([_m4_b]))
+# then invoke m4_unquote(_m4_b($@)), for concatenation with later text.
+m4_define([m4_bmatch],
+[m4_if([$#], 0, [m4_fatal([$0: too few arguments: $#])],
+ [$#], 1, [m4_fatal([$0: too few arguments: $#: $1])],
+ [$#], 2, [$2],
+ [m4_define([_m4_b], m4_pushdef([_m4_b])[m4_define([_m4_b],
+ _m4_defn([_$0]))]_m4_for([_m4_b], [3], m4_eval([($# + 1) / 2 * 2 - 1]),
+ [2], [_$0_([1], m4_decr(_m4_b), _m4_b)])[_m4_b([], [],]m4_dquote(
+ [$]m4_incr(_m4_b))[_m4_popdef([_m4_b]))])m4_unquote(_m4_b($@))])])
+
+m4_define([_m4_bmatch],
+[m4_if(m4_bregexp([$1], [$2]), [-1], [], [[$3]m4_define([$0])])])
+
+m4_define([_m4_bmatch_],
+[[_m4_b([$$1], [$$2], [$$3])]])
+
+
+# m4_cond(TEST1, VAL1, IF-VAL1, TEST2, VAL2, IF-VAL2, ..., [DEFAULT])
+# -------------------------------------------------------------------
+# Similar to m4_if, except that each TEST is expanded when encountered.
+# If the expansion of TESTn matches the string VALn, the result is IF-VALn.
+# The result is DEFAULT if no tests passed. This macro allows
+# short-circuiting of expensive tests, where it pays to arrange quick
+# filter tests to run first.
+#
+# m4_cond already guarantees either 3*n or 3*n + 1 arguments, 1 <= n.
+# We only have to speed up _m4_cond, by building the temporary _m4_c:
+# m4_define([_m4_c], _m4_defn([m4_unquote]))_m4_c([m4_if(($1), [($2)],
+# [[$3]m4_define([_m4_c])])])_m4_c([m4_if(($4), [($5)],
+# [[$6]m4_define([_m4_c])])])..._m4_c([m4_if(($m-2), [($m-1)],
+# [[$m]m4_define([_m4_c])])])_m4_c([[$m+1]]_m4_popdef([_m4_c]))
+# We invoke m4_unquote(_m4_c($@)), for concatenation with later text.
+m4_define([_m4_cond],
+[m4_define([_m4_c], m4_pushdef([_m4_c])[m4_define([_m4_c],
+ _m4_defn([m4_unquote]))]_m4_for([_m4_c], [2], m4_eval([$# / 3 * 3 - 1]), [3],
+ [$0_(m4_decr(_m4_c), _m4_c, m4_incr(_m4_c))])[_m4_c(]m4_dquote(m4_dquote(
+ [$]m4_eval([$# / 3 * 3 + 1])))[_m4_popdef([_m4_c]))])m4_unquote(_m4_c($@))])
+
+m4_define([_m4_cond_],
+[[_m4_c([m4_if(($$1), [($$2)], [[$$3]m4_define([_m4_c])])])]])
+
+# m4_bpatsubsts(STRING, RE1, SUBST1, RE2, SUBST2, ...)
+# ----------------------------------------------------
+# m4 equivalent of
+#
+# $_ = STRING;
+# s/RE1/SUBST1/g;
+# s/RE2/SUBST2/g;
+# ...
+#
+# m4_bpatsubsts already validated an odd number of arguments; we only
+# need to speed up _m4_bpatsubsts. To avoid nesting, we build the
+# temporary _m4_p:
+# m4_define([_m4_p], [$1])m4_define([_m4_p],
+# m4_bpatsubst(m4_dquote(_m4_defn([_m4_p])), [$2], [$3]))m4_define([_m4_p],
+# m4_bpatsubst(m4_dquote(_m4_defn([_m4_p])), [$4], [$5]))m4_define([_m4_p],...
+# m4_bpatsubst(m4_dquote(_m4_defn([_m4_p])), [$m-1], [$m]))m4_unquote(
+# _m4_defn([_m4_p])_m4_popdef([_m4_p]))
+m4_define([_m4_bpatsubsts],
+[m4_define([_m4_p], m4_pushdef([_m4_p])[m4_define([_m4_p],
+ ]m4_dquote([$]1)[)]_m4_for([_m4_p], [3], [$#], [2], [$0_(m4_decr(_m4_p),
+ _m4_p)])[m4_unquote(_m4_defn([_m4_p])_m4_popdef([_m4_p]))])_m4_p($@)])
+
+m4_define([_m4_bpatsubsts_],
+[[m4_define([_m4_p],
+m4_bpatsubst(m4_dquote(_m4_defn([_m4_p])), [$$1], [$$2]))]])
+
+# m4_shiftn(N, ...)
+# -----------------
+# Returns ... shifted N times. Useful for recursive "varargs" constructs.
+#
+# m4_shiftn already validated arguments; we only need to speed up
+# _m4_shiftn. If N is 3, then we build the temporary _m4_s, defined as
+# ,[$5],[$6],...,[$m]_m4_popdef([_m4_s])
+# before calling m4_shift(_m4_s($@)).
+m4_define([_m4_shiftn],
+[m4_if(m4_incr([$1]), [$#], [], [m4_define([_m4_s],
+ m4_pushdef([_m4_s])_m4_for([_m4_s], m4_eval([$1 + 2]), [$#], [1],
+ [[,]m4_dquote([$]_m4_s)])[_m4_popdef([_m4_s])])m4_shift(_m4_s($@))])])
+
+# m4_do(STRING, ...)
+# ------------------
+# This macro invokes all its arguments (in sequence, of course). It is
+# useful for making your macros more structured and readable by dropping
+# unnecessary dnl's and have the macros indented properly.
+#
+# Here, we use the temporary macro _m4_do, defined as
+# $1[]$2[]...[]$n[]_m4_popdef([_m4_do])
+m4_define([m4_do],
+[m4_if([$#], [0], [],
+ [m4_define([_$0], m4_pushdef([_$0])_m4_for([_$0], [1], [$#], [1],
+ [$_$0[[]]])[_m4_popdef([_$0])])_$0($@)])])
+
+# m4_dquote_elt(ARGS)
+# -------------------
+# Return ARGS as an unquoted list of double-quoted arguments.
+#
+# m4_foreach to the rescue. It's easier to shift off the leading comma.
+m4_define([m4_dquote_elt],
+[m4_shift(m4_foreach([_m4_elt], [$@], [,m4_dquote(_m4_defn([_m4_elt]))]))])
+
+# m4_reverse(ARGS)
+# ----------------
+# Output ARGS in reverse order.
+#
+# Invoke _m4_r($@) with the temporary _m4_r built as
+# [$m], [$m-1], ..., [$2], [$1]_m4_popdef([_m4_r])
+m4_define([m4_reverse],
+[m4_if([$#], [0], [], [$#], [1], [[$1]],
+[m4_define([_m4_r], m4_dquote([$$#])m4_pushdef([_m4_r])_m4_for([_m4_r],
+ m4_decr([$#]), [1], [-1],
+ [[, ]m4_dquote([$]_m4_r)])[_m4_popdef([_m4_r])])_m4_r($@)])])
+
+
+# m4_map(MACRO, LIST)
+# -------------------
+# Invoke MACRO($1), MACRO($2) etc. where $1, $2... are the elements
+# of LIST. $1, $2... must in turn be lists, appropriate for m4_apply.
+#
+# m4_map/m4_map_sep only execute once; the speedup comes in fixing
+# _m4_map. The mismatch in () is intentional, since $1 supplies the
+# opening `(' (but it sure looks odd!). Build the temporary _m4_m:
+# $1, [$3])$1, [$4])...$1, [$m])_m4_popdef([_m4_m])
+m4_define([_m4_map],
+[m4_if([$#], [2], [],
+ [m4_define([_m4_m], m4_pushdef([_m4_m])_m4_for([_m4_m], [3], [$#], [1],
+ [$0_([1], _m4_m)])[_m4_popdef([_m4_m])])_m4_m($@)])])
+
+m4_define([_m4_map_],
+[[$$1, [$$2])]])
+
+# m4_transform(EXPRESSION, ARG...)
+# --------------------------------
+# Expand EXPRESSION([ARG]) for each argument. More efficient than
+# m4_foreach([var], [ARG...], [EXPRESSION(m4_defn([var]))])
+#
+# Invoke the temporary macro _m4_transform, defined as:
+# $1([$2])[]$1([$3])[]...$1([$m])[]_m4_popdef([_m4_transform])
+m4_define([m4_transform],
+[m4_if([$#], [0], [m4_fatal([$0: too few arguments: $#])],
+ [$#], [1], [],
+ [m4_define([_$0], m4_pushdef([_$0])_m4_for([_$0], [2], [$#], [1],
+ [_$0_([1], _$0)])[_m4_popdef([_$0])])_$0($@)])])
+
+m4_define([_m4_transform_],
+[[$$1([$$2])[]]])
+
+# m4_transform_pair(EXPRESSION, [END-EXPR = EXPRESSION], ARG...)
+# --------------------------------------------------------------
+# Perform a pairwise grouping of consecutive ARGs, by expanding
+# EXPRESSION([ARG1], [ARG2]). If there are an odd number of ARGs, the
+# final argument is expanded with END-EXPR([ARGn]).
+#
+# Build the temporary macro _m4_transform_pair, with the $2([$m+1])
+# only output if $# is odd:
+# $1([$3], [$4])[]$1([$5], [$6])[]...$1([$m-1],
+# [$m])[]m4_default([$2], [$1])([$m+1])[]_m4_popdef([_m4_transform_pair])
+m4_define([m4_transform_pair],
+[m4_if([$#], [0], [m4_fatal([$0: too few arguments: $#])],
+ [$#], [1], [m4_fatal([$0: too few arguments: $#: $1])],
+ [$#], [2], [],
+ [$#], [3], [m4_default([$2], [$1])([$3])[]],
+ [m4_define([_$0], m4_pushdef([_$0])_m4_for([_$0], [3],
+ m4_eval([$# / 2 * 2 - 1]), [2], [_$0_([1], _$0, m4_incr(_$0))])_$0_end(
+ [1], [2], [$#])[_m4_popdef([_$0])])_$0($@)])])
+
+m4_define([_m4_transform_pair_],
+[[$$1([$$2], [$$3])[]]])
+
+m4_define([_m4_transform_pair_end],
+[m4_if(m4_eval([$3 & 1]), [1], [[m4_default([$$2], [$$1])([$$3])[]]])])
+
+# m4_join(SEP, ARG1, ARG2...)
+# ---------------------------
+# Produce ARG1SEPARG2...SEPARGn. Avoid back-to-back SEP when a given ARG
+# is the empty string. No expansion is performed on SEP or ARGs.
+#
+# Use a self-modifying separator, since we don't know how many
+# arguments might be skipped before a separator is first printed, but
+# be careful if the separator contains $. m4_foreach to the rescue.
+m4_define([m4_join],
+[m4_pushdef([_m4_sep], [m4_define([_m4_sep], _m4_defn([m4_echo]))])]dnl
+[m4_foreach([_m4_arg], [m4_shift($@)],
+ [m4_ifset([_m4_arg], [_m4_sep([$1])_m4_defn([_m4_arg])])])]dnl
+[_m4_popdef([_m4_sep])])
+
+# m4_joinall(SEP, ARG1, ARG2...)
+# ------------------------------
+# Produce ARG1SEPARG2...SEPARGn. An empty ARG results in back-to-back SEP.
+# No expansion is performed on SEP or ARGs.
+#
+# A bit easier than m4_join. m4_foreach to the rescue.
+m4_define([m4_joinall],
+[[$2]m4_if(m4_eval([$# <= 2]), [1], [],
+ [m4_foreach([_m4_arg], [m4_shift2($@)],
+ [[$1]_m4_defn([_m4_arg])])])])
+
+# m4_list_cmp(A, B)
+# -----------------
+# Compare the two lists of integer expressions A and B.
+#
+# m4_list_cmp takes care of any side effects; we only override
+# _m4_list_cmp_raw, where we can safely expand lists multiple times.
+# First, insert padding so that both lists are the same length; the
+# trailing +0 is necessary to handle a missing list. Next, create a
+# temporary macro to perform pairwise comparisons until an inequality
+# is found. For example, m4_list_cmp([1], [1,2]) creates _m4_cmp as
+# m4_if(m4_eval([($1) != ($3)]), [1], [m4_cmp([$1], [$3])],
+# m4_eval([($2) != ($4)]), [1], [m4_cmp([$2], [$4])],
+# [0]_m4_popdef([_m4_cmp], [_m4_size]))
+# then calls _m4_cmp([1+0], [0], [1], [2+0])
+m4_define([_m4_list_cmp_raw],
+[m4_if([$1], [$2], 0, [m4_pushdef(
+ [_m4_size])_m4_list_cmp($1+0_m4_list_pad(m4_count($1), m4_count($2)),
+ $2+0_m4_list_pad(m4_count($2), m4_count($1)))])])
+
+m4_define([_m4_list_pad],
+[m4_if(m4_eval($1 < $2), [1],
+ [_m4_for([_m4_size], m4_incr([$1]), [$2], [1], [,0])])])
+
+m4_define([_m4_list_cmp],
+[m4_define([_m4_size], m4_eval([$# >> 1]))]dnl
+[m4_define([_m4_cmp], m4_pushdef([_m4_cmp])[m4_if(]_m4_for([_m4_cmp],
+ [1], _m4_size, [1], [$0_(_m4_cmp, m4_eval(_m4_cmp + _m4_size))])[
+ [0]_m4_popdef([_m4_cmp], [_m4_size]))])_m4_cmp($@)])
+
+m4_define([_m4_list_cmp_],
+[[m4_eval([($$1) != ($$2)]), [1], [m4_cmp([$$1], [$$2])],
+]])
+
+# m4_max(EXPR, ...)
+# m4_min(EXPR, ...)
+# -----------------
+# Return the decimal value of the maximum (or minimum) in a series of
+# integer expressions.
+#
+# m4_foreach to the rescue; we only need to replace _m4_minmax. Here,
+# we need a temporary macro to track the best answer so far, so that
+# the foreach expression is tractable.
+m4_define([_m4_minmax],
+[m4_pushdef([_m4_best], m4_eval([$2]))m4_foreach([_m4_arg], [m4_shift2($@)],
+ [m4_define([_m4_best], $1(_m4_best, _m4_defn([_m4_arg])))])]dnl
+[_m4_best[]_m4_popdef([_m4_best])])
+
+# m4_set_add_all(SET, VALUE...)
+# -----------------------------
+# Add each VALUE into SET. This is O(n) in the number of VALUEs, and
+# can be faster than calling m4_set_add for each VALUE.
+#
+# m4_foreach to the rescue. If no deletions have occurred, then avoid
+# the speed penalty of m4_set_add.
+m4_define([m4_set_add_all],
+[m4_if([$#], [0], [], [$#], [1], [],
+ [m4_define([_m4_set_size($1)], m4_eval(m4_set_size([$1])
+ + m4_len(m4_foreach([_m4_arg], [m4_shift($@)],
+ m4_ifdef([_m4_set_cleanup($1)],
+ [[m4_set_add([$1], _m4_defn([_m4_arg]))]],
+ [[m4_ifdef([_m4_set([$1],]_m4_defn([_m4_arg])[)], [],
+ [m4_define([_m4_set([$1],]_m4_defn([_m4_arg])[)],
+ [1])m4_pushdef([_m4_set([$1])],
+ _m4_defn([_m4_arg]))-])]])))))])])
diff --git a/tools/mhmake/src/bisondata/m4sugar/m4sugar.m4 b/tools/mhmake/src/bisondata/m4sugar/m4sugar.m4
new file mode 100644
index 000000000..291267c33
--- /dev/null
+++ b/tools/mhmake/src/bisondata/m4sugar/m4sugar.m4
@@ -0,0 +1,2789 @@
+divert(-1)# -*- Autoconf -*-
+# This file is part of Autoconf.
+# Base M4 layer.
+# Requires GNU M4.
+#
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
+# 2008 Free Software Foundation, Inc.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# As a special exception, the Free Software Foundation gives unlimited
+# permission to copy, distribute and modify the configure scripts that
+# are the output of Autoconf. You need not follow the terms of the GNU
+# General Public License when using or distributing such scripts, even
+# though portions of the text of Autoconf appear in them. The GNU
+# General Public License (GPL) does govern all other use of the material
+# that constitutes the Autoconf program.
+#
+# Certain portions of the Autoconf source text are designed to be copied
+# (in certain cases, depending on the input) into the output of
+# Autoconf. We call these the "data" portions. The rest of the Autoconf
+# source text consists of comments plus executable code that decides which
+# of the data portions to output in any given case. We call these
+# comments and executable code the "non-data" portions. Autoconf never
+# copies any of the non-data portions into its output.
+#
+# This special exception to the GPL applies to versions of Autoconf
+# released by the Free Software Foundation. When you make and
+# distribute a modified version of Autoconf, you may extend this special
+# exception to the GPL to apply to your modified version as well, *unless*
+# your modified version has the potential to copy into its output some
+# of the text that was the non-data portion of the version that you started
+# with. (In other words, unless your change moves or copies text from
+# the non-data portions to the data portions.) If your modification has
+# such potential, you must delete any notice of this special exception
+# to the GPL from your modified version.
+#
+# Written by Akim Demaille.
+#
+
+# Set the quotes, whatever the current quoting system.
+changequote()
+changequote([, ])
+
+# Some old m4's don't support m4exit. But they provide
+# equivalent functionality by core dumping because of the
+# long macros we define.
+ifdef([__gnu__], ,
+[errprint(M4sugar requires GNU M4. Install it before installing M4sugar or
+set the M4 environment variable to its absolute file name.)
+m4exit(2)])
+
+
+## ------------------------------- ##
+## 1. Simulate --prefix-builtins. ##
+## ------------------------------- ##
+
+# m4_define
+# m4_defn
+# m4_undefine
+define([m4_define], defn([define]))
+define([m4_defn], defn([defn]))
+define([m4_undefine], defn([undefine]))
+
+m4_undefine([define])
+m4_undefine([defn])
+m4_undefine([undefine])
+
+
+# m4_copy(SRC, DST)
+# -----------------
+# Define DST as the definition of SRC.
+# What's the difference between:
+# 1. m4_copy([from], [to])
+# 2. m4_define([to], [from($@)])
+# Well, obviously 1 is more expensive in space. Maybe 2 is more expensive
+# in time, but because of the space cost of 1, it's not that obvious.
+# Nevertheless, one huge difference is the handling of `$0'. If `from'
+# uses `$0', then with 1, `to''s `$0' is `to', while it is `from' in 2.
+# The user would certainly prefer to see `to'.
+m4_define([m4_copy],
+[m4_define([$2], m4_defn([$1]))])
+
+
+# m4_rename(SRC, DST)
+# -------------------
+# Rename the macro SRC to DST.
+m4_define([m4_rename],
+[m4_copy([$1], [$2])m4_undefine([$1])])
+
+
+# m4_rename_m4(MACRO-NAME)
+# ------------------------
+# Rename MACRO-NAME to m4_MACRO-NAME.
+m4_define([m4_rename_m4],
+[m4_rename([$1], [m4_$1])])
+
+
+# m4_copy_unm4(m4_MACRO-NAME)
+# ---------------------------
+# Copy m4_MACRO-NAME to MACRO-NAME.
+m4_define([m4_copy_unm4],
+[m4_copy([$1], m4_bpatsubst([$1], [^m4_\(.*\)], [[\1]]))])
+
+
+# Some m4 internals have names colliding with tokens we might use.
+# Rename them a` la `m4 --prefix-builtins'. Conditionals first, since
+# some subsequent renames are conditional.
+m4_rename_m4([ifdef])
+m4_rename([ifelse], [m4_if])
+
+m4_rename_m4([builtin])
+m4_rename_m4([changecom])
+m4_rename_m4([changequote])
+m4_ifdef([changeword],dnl conditionally available in 1.4.x
+[m4_undefine([changeword])])
+m4_rename_m4([debugfile])
+m4_rename_m4([debugmode])
+m4_rename_m4([decr])
+m4_undefine([divert])
+m4_rename_m4([divnum])
+m4_rename_m4([dumpdef])
+m4_rename_m4([errprint])
+m4_rename_m4([esyscmd])
+m4_rename_m4([eval])
+m4_rename_m4([format])
+m4_undefine([include])
+m4_rename_m4([incr])
+m4_rename_m4([index])
+m4_rename_m4([indir])
+m4_rename_m4([len])
+m4_rename([m4exit], [m4_exit])
+m4_undefine([m4wrap])
+m4_ifdef([mkstemp],dnl added in M4 1.4.8
+[m4_rename_m4([mkstemp])
+m4_copy([m4_mkstemp], [m4_maketemp])
+m4_undefine([maketemp])],
+[m4_rename_m4([maketemp])
+m4_copy([m4_maketemp], [m4_mkstemp])])
+m4_rename([patsubst], [m4_bpatsubst])
+m4_rename_m4([popdef])
+m4_rename_m4([pushdef])
+m4_rename([regexp], [m4_bregexp])
+m4_rename_m4([shift])
+m4_undefine([sinclude])
+m4_rename_m4([substr])
+m4_ifdef([symbols],dnl present only in alpha-quality 1.4o
+[m4_rename_m4([symbols])])
+m4_rename_m4([syscmd])
+m4_rename_m4([sysval])
+m4_rename_m4([traceoff])
+m4_rename_m4([traceon])
+m4_rename_m4([translit])
+m4_undefine([undivert])
+
+
+## ------------------- ##
+## 2. Error messages. ##
+## ------------------- ##
+
+
+# m4_location
+# -----------
+m4_define([m4_location],
+[__file__:__line__])
+
+
+# m4_errprintn(MSG)
+# -----------------
+# Same as `errprint', but with the missing end of line.
+m4_define([m4_errprintn],
+[m4_errprint([$1
+])])
+
+
+# m4_warning(MSG)
+# ---------------
+# Warn the user.
+m4_define([m4_warning],
+[m4_errprintn(m4_location[: warning: $1])])
+
+
+# m4_fatal(MSG, [EXIT-STATUS])
+# ----------------------------
+# Fatal the user. :)
+m4_define([m4_fatal],
+[m4_errprintn(m4_location[: error: $1])dnl
+m4_expansion_stack_dump()dnl
+m4_exit(m4_if([$2],, 1, [$2]))])
+
+
+# m4_assert(EXPRESSION, [EXIT-STATUS = 1])
+# ----------------------------------------
+# This macro ensures that EXPRESSION evaluates to true, and exits if
+# EXPRESSION evaluates to false.
+m4_define([m4_assert],
+[m4_if(m4_eval([$1]), 0,
+ [m4_fatal([assert failed: $1], [$2])])])
+
+
+
+## ------------- ##
+## 3. Warnings. ##
+## ------------- ##
+
+
+# _m4_warn(CATEGORY, MESSAGE, STACK-TRACE)
+# ----------------------------------------
+# Report a MESSAGE to the user if the CATEGORY of warnings is enabled.
+# This is for traces only.
+# The STACK-TRACE is a \n-separated list of "LOCATION: MESSAGE".
+#
+# Within m4, the macro is a no-op. This macro really matters
+# when autom4te post-processes the trace output.
+m4_define([_m4_warn], [])
+
+
+# m4_warn(CATEGORY, MESSAGE)
+# --------------------------
+# Report a MESSAGE to the user if the CATEGORY of warnings is enabled.
+m4_define([m4_warn],
+[_m4_warn([$1], [$2],
+m4_ifdef([m4_expansion_stack],
+ [_m4_defn([m4_expansion_stack])
+m4_location[: the top level]]))dnl
+])
+
+
+
+## ------------------- ##
+## 4. File inclusion. ##
+## ------------------- ##
+
+
+# We also want to neutralize include (and sinclude for symmetry),
+# but we want to extend them slightly: warn when a file is included
+# several times. This is, in general, a dangerous operation, because
+# too many people forget to quote the first argument of m4_define.
+#
+# For instance in the following case:
+# m4_define(foo, [bar])
+# then a second reading will turn into
+# m4_define(bar, [bar])
+# which is certainly not what was meant.
+
+# m4_include_unique(FILE)
+# -----------------------
+# Declare that the FILE was loading; and warn if it has already
+# been included.
+m4_define([m4_include_unique],
+[m4_ifdef([m4_include($1)],
+ [m4_warn([syntax], [file `$1' included several times])])dnl
+m4_define([m4_include($1)])])
+
+
+# m4_include(FILE)
+# ----------------
+# Like the builtin include, but warns against multiple inclusions.
+m4_define([m4_include],
+[m4_include_unique([$1])dnl
+m4_builtin([include], [$1])])
+
+
+# m4_sinclude(FILE)
+# -----------------
+# Like the builtin sinclude, but warns against multiple inclusions.
+m4_define([m4_sinclude],
+[m4_include_unique([$1])dnl
+m4_builtin([sinclude], [$1])])
+
+
+
+## ------------------------------------ ##
+## 5. Additional branching constructs. ##
+## ------------------------------------ ##
+
+# Both `m4_ifval' and `m4_ifset' tests against the empty string. The
+# difference is that `m4_ifset' is specialized on macros.
+#
+# In case of arguments of macros, eg. $1, it makes little difference.
+# In the case of a macro `FOO', you don't want to check `m4_ifval(FOO,
+# TRUE)', because if `FOO' expands with commas, there is a shifting of
+# the arguments. So you want to run `m4_ifval([FOO])', but then you just
+# compare the *string* `FOO' against `', which, of course fails.
+#
+# So you want the variation `m4_ifset' that expects a macro name as $1.
+# If this macro is both defined and defined to a non empty value, then
+# it runs TRUE, etc.
+
+
+# m4_ifval(COND, [IF-TRUE], [IF-FALSE])
+# -------------------------------------
+# If COND is not the empty string, expand IF-TRUE, otherwise IF-FALSE.
+# Comparable to m4_ifdef.
+m4_define([m4_ifval],
+[m4_if([$1], [], [$3], [$2])])
+
+
+# m4_n(TEXT)
+# ----------
+# If TEXT is not empty, return TEXT and a new line, otherwise nothing.
+m4_define([m4_n],
+[m4_if([$1],
+ [], [],
+ [$1
+])])
+
+
+# m4_ifvaln(COND, [IF-TRUE], [IF-FALSE])
+# --------------------------------------
+# Same as `m4_ifval', but add an extra newline to IF-TRUE or IF-FALSE
+# unless that argument is empty.
+m4_define([m4_ifvaln],
+[m4_if([$1],
+ [], [m4_n([$3])],
+ [m4_n([$2])])])
+
+
+# m4_ifset(MACRO, [IF-TRUE], [IF-FALSE])
+# --------------------------------------
+# If MACRO has no definition, or of its definition is the empty string,
+# expand IF-FALSE, otherwise IF-TRUE.
+m4_define([m4_ifset],
+[m4_ifdef([$1],
+ [m4_ifval(_m4_defn([$1]), [$2], [$3])],
+ [$3])])
+
+
+# m4_ifndef(NAME, [IF-NOT-DEFINED], [IF-DEFINED])
+# -----------------------------------------------
+m4_define([m4_ifndef],
+[m4_ifdef([$1], [$3], [$2])])
+
+
+# m4_case(SWITCH, VAL1, IF-VAL1, VAL2, IF-VAL2, ..., DEFAULT)
+# -----------------------------------------------------------
+# m4 equivalent of
+# switch (SWITCH)
+# {
+# case VAL1:
+# IF-VAL1;
+# break;
+# case VAL2:
+# IF-VAL2;
+# break;
+# ...
+# default:
+# DEFAULT;
+# break;
+# }.
+# All the values are optional, and the macro is robust to active
+# symbols properly quoted.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_case],
+[m4_if([$#], 0, [],
+ [$#], 1, [],
+ [$#], 2, [$2],
+ [$1], [$2], [$3],
+ [$0([$1], m4_shift3($@))])])
+
+
+# m4_bmatch(SWITCH, RE1, VAL1, RE2, VAL2, ..., DEFAULT)
+# -----------------------------------------------------
+# m4 equivalent of
+#
+# if (SWITCH =~ RE1)
+# VAL1;
+# elif (SWITCH =~ RE2)
+# VAL2;
+# elif ...
+# ...
+# else
+# DEFAULT
+#
+# All the values are optional, and the macro is robust to active symbols
+# properly quoted.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_bmatch],
+[m4_if([$#], 0, [m4_fatal([$0: too few arguments: $#])],
+ [$#], 1, [m4_fatal([$0: too few arguments: $#: $1])],
+ [$#], 2, [$2],
+ [m4_if(m4_bregexp([$1], [$2]), -1, [$0([$1], m4_shift3($@))],
+ [$3])])])
+
+
+# m4_car(LIST)
+# m4_cdr(LIST)
+# ------------
+# Manipulate m4 lists.
+m4_define([m4_car], [[$1]])
+m4_define([m4_cdr],
+[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
+ [$#], 1, [],
+ [m4_dquote(m4_shift($@))])])
+
+# _m4_cdr(LIST)
+# -------------
+# Like m4_cdr, except include a leading comma unless only one element
+# remains. Why? Because comparing a large list against [] is more
+# expensive in expansion time than comparing the number of arguments; so
+# _m4_cdr can be used to reduce the number of arguments when it is time
+# to end recursion.
+m4_define([_m4_cdr],
+[m4_if([$#], 1, [],
+ [, m4_dquote(m4_shift($@))])])
+
+
+
+# m4_cond(TEST1, VAL1, IF-VAL1, TEST2, VAL2, IF-VAL2, ..., [DEFAULT])
+# -------------------------------------------------------------------
+# Similar to m4_if, except that each TEST is expanded when encountered.
+# If the expansion of TESTn matches the string VALn, the result is IF-VALn.
+# The result is DEFAULT if no tests passed. This macro allows
+# short-circuiting of expensive tests, where it pays to arrange quick
+# filter tests to run first.
+#
+# For an example, consider a previous implementation of _AS_QUOTE_IFELSE:
+#
+# m4_if(m4_index([$1], [\]), [-1], [$2],
+# m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
+# m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
+# m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
+# m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
+# [$2])
+#
+# Here, m4_index is computed 5 times, and m4_eval 4, even if $1 contains
+# no backslash. It is more efficient to do:
+#
+# m4_cond([m4_index([$1], [\])], [-1], [$2],
+# [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
+# [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
+# [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
+# [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
+# [$2])
+#
+# In the common case of $1 with no backslash, only one m4_index expansion
+# occurs, and m4_eval is avoided altogether.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_cond],
+[m4_if([$#], [0], [m4_fatal([$0: cannot be called without arguments])],
+ [$#], [1], [$1],
+ m4_eval([$# % 3]), [2], [m4_fatal([$0: missing an argument])],
+ [_$0($@)])])
+
+m4_define([_m4_cond],
+[m4_if(($1), [($2)], [$3],
+ [$#], [3], [],
+ [$#], [4], [$4],
+ [$0(m4_shift3($@))])])
+
+
+## ---------------------------------------- ##
+## 6. Enhanced version of some primitives. ##
+## ---------------------------------------- ##
+
+# m4_bpatsubsts(STRING, RE1, SUBST1, RE2, SUBST2, ...)
+# ----------------------------------------------------
+# m4 equivalent of
+#
+# $_ = STRING;
+# s/RE1/SUBST1/g;
+# s/RE2/SUBST2/g;
+# ...
+#
+# All the values are optional, and the macro is robust to active symbols
+# properly quoted.
+#
+# I would have liked to name this macro `m4_bpatsubst', unfortunately,
+# due to quotation problems, I need to double quote $1 below, therefore
+# the anchors are broken :( I can't let users be trapped by that.
+#
+# Recall that m4_shift3 always results in an argument. Hence, we need
+# to distinguish between a final deletion vs. ending recursion.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_bpatsubsts],
+[m4_if([$#], 0, [m4_fatal([$0: too few arguments: $#])],
+ [$#], 1, [m4_fatal([$0: too few arguments: $#: $1])],
+ [$#], 2, [m4_unquote(m4_builtin([patsubst], [[$1]], [$2]))],
+ [$#], 3, [m4_unquote(m4_builtin([patsubst], [[$1]], [$2], [$3]))],
+ [_$0($@m4_if(m4_eval($# & 1), 0, [,]))])])
+m4_define([_m4_bpatsubsts],
+[m4_if([$#], 2, [$1],
+ [$0(m4_builtin([patsubst], [[$1]], [$2], [$3]),
+ m4_shift3($@))])])
+
+
+# m4_define_default(MACRO, VALUE)
+# -------------------------------
+# If MACRO is undefined, set it to VALUE.
+m4_define([m4_define_default],
+[m4_ifndef([$1], [m4_define($@)])])
+
+
+# m4_default(EXP1, EXP2)
+# ----------------------
+# Returns EXP1 if non empty, otherwise EXP2.
+#
+# This macro is called on hot paths, so inline the contents of m4_ifval,
+# for one less round of expansion.
+m4_define([m4_default],
+[m4_if([$1], [], [$2], [$1])])
+
+
+# m4_defn(NAME)
+# -------------
+# Like the original, except guarantee a warning when using something which is
+# undefined (unlike M4 1.4.x). This replacement is not a full-featured
+# replacement: if any of the defined macros contain unbalanced quoting, but
+# when pasted together result in a well-quoted string, then only native m4
+# support is able to get it correct. But that's where quadrigraphs come in
+# handy, if you really need unbalanced quotes inside your macros.
+#
+# This macro is called frequently, so minimize the amount of additional
+# expansions by skipping m4_ifndef. Better yet, if __m4_version__ exists,
+# (added in M4 1.6), then let m4 do the job for us (see m4_init).
+#
+# _m4_defn is for internal use only - it bypasses the wrapper, so it
+# must only be used on one argument at a time, and only on macros
+# known to be defined. Make sure this still works if the user renames
+# m4_defn but not _m4_defn.
+m4_copy([m4_defn], [_m4_defn])
+m4_define([m4_defn],
+[m4_if([$#], [0], [[$0]],
+ [$#], [1], [m4_ifdef([$1], [_m4_defn([$1])],
+ [m4_fatal([$0: undefined macro: $1])])],
+ [m4_foreach([_m4_macro], [$@], [$0(_m4_defn([_m4_macro]))])])])
+
+
+# _m4_dumpdefs_up(NAME)
+# ---------------------
+m4_define([_m4_dumpdefs_up],
+[m4_ifdef([$1],
+ [m4_pushdef([_m4_dumpdefs], _m4_defn([$1]))dnl
+m4_dumpdef([$1])dnl
+_m4_popdef([$1])dnl
+_m4_dumpdefs_up([$1])])])
+
+
+# _m4_dumpdefs_down(NAME)
+# -----------------------
+m4_define([_m4_dumpdefs_down],
+[m4_ifdef([_m4_dumpdefs],
+ [m4_pushdef([$1], _m4_defn([_m4_dumpdefs]))dnl
+_m4_popdef([_m4_dumpdefs])dnl
+_m4_dumpdefs_down([$1])])])
+
+
+# m4_dumpdefs(NAME)
+# -----------------
+# Similar to `m4_dumpdef(NAME)', but if NAME was m4_pushdef'ed, display its
+# value stack (most recent displayed first).
+m4_define([m4_dumpdefs],
+[_m4_dumpdefs_up([$1])dnl
+_m4_dumpdefs_down([$1])])
+
+
+# m4_popdef(NAME)
+# ---------------
+# Like the original, except guarantee a warning when using something which is
+# undefined (unlike M4 1.4.x).
+#
+# This macro is called frequently, so minimize the amount of additional
+# expansions by skipping m4_ifndef. Better yet, if __m4_version__ exists,
+# (added in M4 1.6), then let m4 do the job for us (see m4_init).
+#
+# _m4_popdef is for internal use only - it bypasses the wrapper, so it
+# must only be used on macros known to be defined. Make sure this
+# still works if the user renames m4_popdef but not _m4_popdef.
+m4_copy([m4_popdef], [_m4_popdef])
+m4_define([m4_popdef],
+[m4_if([$#], [0], [[$0]],
+ [$#], [1], [m4_ifdef([$1], [_m4_popdef([$1])],
+ [m4_fatal([$0: undefined macro: $1])])],
+ [m4_foreach([_m4_macro], [$@], [$0(_m4_defn([_m4_macro]))])])])
+
+
+# m4_shiftn(N, ...)
+# -----------------
+# Returns ... shifted N times. Useful for recursive "varargs" constructs.
+#
+# Autoconf does not use this macro, because it is inherently slower than
+# calling the common cases of m4_shift2 or m4_shift3 directly. But it
+# might as well be fast for other clients, such as Libtool. One way to
+# do this is to expand $@ only once in _m4_shiftn (otherwise, for long
+# lists, the expansion of m4_if takes twice as much memory as what the
+# list itself occupies, only to throw away the unused branch). The end
+# result is strictly equivalent to
+# m4_if([$1], 1, [m4_shift(,m4_shift(m4_shift($@)))],
+# [_m4_shiftn(m4_decr([$1]), m4_shift(m4_shift($@)))])
+# but with the final `m4_shift(m4_shift($@)))' shared between the two
+# paths. The first leg uses a no-op m4_shift(,$@) to balance out the ().
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_shiftn],
+[m4_assert(0 < $1 && $1 < $#)_$0($@)])
+
+m4_define([_m4_shiftn],
+[m4_if([$1], 1, [m4_shift(],
+ [$0(m4_decr([$1])]), m4_shift(m4_shift($@)))])
+
+# m4_shift2(...)
+# m4_shift3(...)
+# -----------------
+# Returns ... shifted twice, and three times. Faster than m4_shiftn.
+m4_define([m4_shift2], [m4_shift(m4_shift($@))])
+m4_define([m4_shift3], [m4_shift(m4_shift(m4_shift($@)))])
+
+# _m4_shift2(...)
+# _m4_shift3(...)
+# ---------------
+# Like m4_shift2 or m4_shift3, except include a leading comma unless shifting
+# consumes all arguments. Why? Because in recursion, it is nice to
+# distinguish between 1 element left and 0 elements left, based on how many
+# arguments this shift expands to.
+m4_define([_m4_shift2],
+[m4_if([$#], [2], [],
+ [, m4_shift(m4_shift($@))])])
+m4_define([_m4_shift3],
+[m4_if([$#], [3], [],
+ [, m4_shift(m4_shift(m4_shift($@)))])])
+
+
+# m4_undefine(NAME)
+# -----------------
+# Like the original, except guarantee a warning when using something which is
+# undefined (unlike M4 1.4.x).
+#
+# This macro is called frequently, so minimize the amount of additional
+# expansions by skipping m4_ifndef. Better yet, if __m4_version__ exists,
+# (added in M4 1.6), then let m4 do the job for us (see m4_init).
+#
+# _m4_undefine is for internal use only - it bypasses the wrapper, so
+# it must only be used on macros known to be defined. Make sure this
+# still works if the user renames m4_undefine but not _m4_undefine.
+m4_copy([m4_undefine], [_m4_undefine])
+m4_define([m4_undefine],
+[m4_if([$#], [0], [[$0]],
+ [$#], [1], [m4_ifdef([$1], [_m4_undefine([$1])],
+ [m4_fatal([$0: undefined macro: $1])])],
+ [m4_foreach([_m4_macro], [$@], [$0(_m4_defn([_m4_macro]))])])])
+
+# _m4_wrap(PRE, POST)
+# -------------------
+# Helper macro for m4_wrap and m4_wrap_lifo. Allows nested calls to
+# m4_wrap within wrapped text. Use _m4_defn and _m4_popdef for speed.
+m4_define([_m4_wrap],
+[m4_ifdef([$0_text],
+ [m4_define([$0_text], [$1]_m4_defn([$0_text])[$2])],
+ [m4_builtin([m4wrap], [m4_unquote(
+ _m4_defn([$0_text])_m4_popdef([$0_text]))])m4_define([$0_text], [$1$2])])])
+
+# m4_wrap(TEXT)
+# -------------
+# Append TEXT to the list of hooks to be executed at the end of input.
+# Whereas the order of the original may be LIFO in the underlying m4,
+# this version is always FIFO.
+m4_define([m4_wrap],
+[_m4_wrap([], [$1[]])])
+
+# m4_wrap_lifo(TEXT)
+# ------------------
+# Prepend TEXT to the list of hooks to be executed at the end of input.
+# Whereas the order of m4_wrap may be FIFO in the underlying m4, this
+# version is always LIFO.
+m4_define([m4_wrap_lifo],
+[_m4_wrap([$1[]])])
+
+## ------------------------- ##
+## 7. Quoting manipulation. ##
+## ------------------------- ##
+
+
+# m4_apply(MACRO, LIST)
+# ---------------------
+# Invoke MACRO, with arguments provided from the quoted list of
+# comma-separated quoted arguments. If LIST is empty, invoke MACRO
+# without arguments. The expansion will not be concatenated with
+# subsequent text.
+m4_define([m4_apply],
+[m4_if([$2], [], [$1], [$1($2)])[]])
+
+# _m4_apply(MACRO, LIST)
+# ----------------------
+# Like m4_apply, except do nothing if LIST is empty.
+m4_define([_m4_apply],
+[m4_if([$2], [], [], [$1($2)[]])])
+
+
+# m4_count(ARGS)
+# --------------
+# Return a count of how many ARGS are present.
+m4_define([m4_count], [$#])
+
+
+# m4_do(STRING, ...)
+# ------------------
+# This macro invokes all its arguments (in sequence, of course). It is
+# useful for making your macros more structured and readable by dropping
+# unnecessary dnl's and have the macros indented properly. No concatenation
+# occurs after a STRING; use m4_unquote(m4_join(,STRING)) for that.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_do],
+[m4_if([$#], 0, [],
+ [$#], 1, [$1[]],
+ [$1[]$0(m4_shift($@))])])
+
+
+# m4_dquote(ARGS)
+# ---------------
+# Return ARGS as a quoted list of quoted arguments.
+m4_define([m4_dquote], [[$@]])
+
+
+# m4_dquote_elt(ARGS)
+# -------------------
+# Return ARGS as an unquoted list of double-quoted arguments.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_dquote_elt],
+[m4_if([$#], [0], [],
+ [$#], [1], [[[$1]]],
+ [[[$1]],$0(m4_shift($@))])])
+
+
+# m4_echo(ARGS)
+# -------------
+# Return the ARGS, with the same level of quoting. Whitespace after
+# unquoted commas are consumed.
+m4_define([m4_echo], [$@])
+
+
+# m4_expand(ARG)
+# --------------
+# Return the expansion of ARG as a single string. Unlike m4_quote($1), this
+# correctly preserves whitespace following single-quoted commas that appeared
+# within ARG.
+#
+# m4_define([active], [ACT, IVE])
+# m4_define([active2], [[ACT, IVE]])
+# m4_quote(active, active2)
+# => ACT,IVE,ACT, IVE
+# m4_expand([active, active2])
+# => ACT, IVE, ACT, IVE
+#
+# Unfortunately, due to limitations in m4, ARG must expand to something
+# with balanced quotes (use quadrigraphs to get around this). The input
+# is not likely to have unbalanced -=<{(/)}>=- quotes, and it is possible
+# to have unbalanced (), provided it was specified with proper [] quotes.
+#
+# Exploit that extra () will group unquoted commas and the following
+# whitespace, then convert () to []. m4_bpatsubst can't handle newlines
+# inside $1, and m4_substr strips quoting. So we (ab)use m4_changequote.
+m4_define([m4_expand], [_$0(-=<{($1)}>=-)])
+m4_define([_m4_expand],
+[m4_changequote([-=<{(], [)}>=-])$1m4_changequote([, ])])
+
+
+# m4_ignore(ARGS)
+# ---------------
+# Expands to nothing. Useful for conditionally ignoring an arbitrary
+# number of arguments (see _m4_list_cmp for an example).
+m4_define([m4_ignore])
+
+
+# m4_make_list(ARGS)
+# ------------------
+# Similar to m4_dquote, this creates a quoted list of quoted ARGS. This
+# version is less efficient than m4_dquote, but separates each argument
+# with a comma and newline, rather than just comma, for readability.
+# When developing an m4sugar algorithm, you could temporarily use
+# m4_pushdef([m4_dquote],m4_defn([m4_make_list]))
+# around your code to make debugging easier.
+m4_define([m4_make_list], [m4_join([,
+], m4_dquote_elt($@))])
+
+
+# m4_noquote(STRING)
+# ------------------
+# Return the result of ignoring all quotes in STRING and invoking the
+# macros it contains. Amongst other things, this is useful for enabling
+# macro invocations inside strings with [] blocks (for instance regexps
+# and help-strings). On the other hand, since all quotes are disabled,
+# any macro expanded during this time that relies on nested [] quoting
+# will likely crash and burn. This macro is seldom useful; consider
+# m4_unquote or m4_expand instead.
+m4_define([m4_noquote],
+[m4_changequote([-=<{(],[)}>=-])$1-=<{()}>=-m4_changequote([,])])
+
+
+# m4_quote(ARGS)
+# --------------
+# Return ARGS as a single argument. Any whitespace after unquoted commas
+# is stripped. There is always output, even when there were no arguments.
+#
+# It is important to realize the difference between `m4_quote(exp)' and
+# `[exp]': in the first case you obtain the quoted *result* of the
+# expansion of EXP, while in the latter you just obtain the string
+# `exp'.
+m4_define([m4_quote], [[$*]])
+
+
+# _m4_quote(ARGS)
+# ---------------
+# Like m4_quote, except that when there are no arguments, there is no
+# output. For conditional scenarios (such as passing _m4_quote as the
+# macro name in m4_mapall), this feature can be used to distinguish between
+# one argument of the empty string vs. no arguments. However, in the
+# normal case with arguments present, this is less efficient than m4_quote.
+m4_define([_m4_quote],
+[m4_if([$#], [0], [], [[$*]])])
+
+
+# m4_reverse(ARGS)
+# ----------------
+# Output ARGS in reverse order.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_reverse],
+[m4_if([$#], [0], [], [$#], [1], [[$1]],
+ [$0(m4_shift($@)), [$1]])])
+
+
+# m4_unquote(ARGS)
+# ----------------
+# Remove one layer of quotes from each ARG, performing one level of
+# expansion. For one argument, m4_unquote([arg]) is more efficient than
+# m4_do([arg]), but for multiple arguments, the difference is that
+# m4_unquote separates arguments with commas while m4_do concatenates.
+# Follow this macro with [] if concatenation with subsequent text is
+# undesired.
+m4_define([m4_unquote], [$*])
+
+
+## -------------------------- ##
+## 8. Implementing m4 loops. ##
+## -------------------------- ##
+
+
+# m4_for(VARIABLE, FIRST, LAST, [STEP = +/-1], EXPRESSION)
+# --------------------------------------------------------
+# Expand EXPRESSION defining VARIABLE to FROM, FROM + 1, ..., TO with
+# increments of STEP. Both limits are included, and bounds are
+# checked for consistency. The algorithm is robust to indirect
+# VARIABLE names. Changing VARIABLE inside EXPRESSION will not impact
+# the number of iterations.
+#
+# Uses _m4_defn for speed, and avoid dnl in the macro body.
+m4_define([m4_for],
+[m4_pushdef([$1], m4_eval([$2]))]dnl
+[m4_cond([m4_eval(([$3]) > ([$2]))], 1,
+ [m4_pushdef([_m4_step], m4_eval(m4_default([$4],
+ 1)))m4_assert(_m4_step > 0)_$0([$1], _m4_defn([$1]),
+ m4_eval((([$3]) - ([$2])) / _m4_step * _m4_step + ([$2])),
+ _m4_step, [$5])],
+ [m4_eval(([$3]) < ([$2]))], 1,
+ [m4_pushdef([_m4_step], m4_eval(m4_default([$4],
+ -1)))m4_assert(_m4_step < 0)_$0([$1], _m4_defn([$1]),
+ m4_eval((([$2]) - ([$3])) / -(_m4_step) * _m4_step + ([$2])),
+ _m4_step, [$5])],
+ [m4_pushdef([_m4_step])$5])[]]dnl
+[m4_popdef([_m4_step], [$1])])
+
+
+# _m4_for(VARIABLE, COUNT, LAST, STEP, EXPRESSION)
+# ------------------------------------------------
+# Core of the loop, no consistency checks, all arguments are plain
+# numbers. Define VARIABLE to COUNT, expand EXPRESSION, then alter
+# COUNT by STEP and iterate if COUNT is not LAST.
+m4_define([_m4_for],
+[m4_define([$1], [$2])$5[]m4_if([$2], [$3], [],
+ [$0([$1], m4_eval([$2 + $4]), [$3], [$4], [$5])])])
+
+
+# Implementing `foreach' loops in m4 is much more tricky than it may
+# seem. For example, the old M4 1.4.4 manual had an incorrect example,
+# which looked like this (when translated to m4sugar):
+#
+# | # foreach(VAR, (LIST), STMT)
+# | m4_define([foreach],
+# | [m4_pushdef([$1])_foreach([$1], [$2], [$3])m4_popdef([$1])])
+# | m4_define([_arg1], [$1])
+# | m4_define([_foreach],
+# | [m4_if([$2], [()], ,
+# | [m4_define([$1], _arg1$2)$3[]_foreach([$1], (m4_shift$2), [$3])])])
+#
+# But then if you run
+#
+# | m4_define(a, 1)
+# | m4_define(b, 2)
+# | m4_define(c, 3)
+# | foreach([f], [([a], [(b], [c)])], [echo f
+# | ])
+#
+# it gives
+#
+# => echo 1
+# => echo (2,3)
+#
+# which is not what is expected.
+#
+# Of course the problem is that many quotes are missing. So you add
+# plenty of quotes at random places, until you reach the expected
+# result. Alternatively, if you are a quoting wizard, you directly
+# reach the following implementation (but if you really did, then
+# apply to the maintenance of m4sugar!).
+#
+# | # foreach(VAR, (LIST), STMT)
+# | m4_define([foreach], [m4_pushdef([$1])_foreach($@)m4_popdef([$1])])
+# | m4_define([_arg1], [[$1]])
+# | m4_define([_foreach],
+# | [m4_if($2, [()], ,
+# | [m4_define([$1], [_arg1$2])$3[]_foreach([$1], [(m4_shift$2)], [$3])])])
+#
+# which this time answers
+#
+# => echo a
+# => echo (b
+# => echo c)
+#
+# Bingo!
+#
+# Well, not quite.
+#
+# With a better look, you realize that the parens are more a pain than
+# a help: since anyway you need to quote properly the list, you end up
+# with always using an outermost pair of parens and an outermost pair
+# of quotes. Rejecting the parens both eases the implementation, and
+# simplifies the use:
+#
+# | # foreach(VAR, (LIST), STMT)
+# | m4_define([foreach], [m4_pushdef([$1])_foreach($@)m4_popdef([$1])])
+# | m4_define([_arg1], [$1])
+# | m4_define([_foreach],
+# | [m4_if($2, [], ,
+# | [m4_define([$1], [_arg1($2)])$3[]_foreach([$1], [m4_shift($2)], [$3])])])
+#
+#
+# Now, just replace the `$2' with `m4_quote($2)' in the outer `m4_if'
+# to improve robustness, and you come up with a nice implementation
+# that doesn't require extra parentheses in the user's LIST.
+#
+# But wait - now the algorithm is quadratic, because every recursion of
+# the algorithm keeps the entire LIST and merely adds another m4_shift to
+# the quoted text. If the user has a lot of elements in LIST, you can
+# bring the system to its knees with the memory m4 then requires, or trip
+# the m4 --nesting-limit recursion factor. The only way to avoid
+# quadratic growth is ensure m4_shift is expanded prior to the recursion.
+# Hence the design below.
+#
+# The M4 manual now includes a chapter devoted to this issue, with
+# the lessons learned from m4sugar. And still, this design is only
+# optimal for M4 1.6; see foreach.m4 for yet more comments on why
+# M4 1.4.x uses yet another implementation.
+
+
+# m4_foreach(VARIABLE, LIST, EXPRESSION)
+# --------------------------------------
+#
+# Expand EXPRESSION assigning each value of the LIST to VARIABLE.
+# LIST should have the form `item_1, item_2, ..., item_n', i.e. the
+# whole list must *quoted*. Quote members too if you don't want them
+# to be expanded.
+#
+# This macro is robust to active symbols:
+# | m4_define(active, [ACT, IVE])
+# | m4_foreach(Var, [active, active], [-Var-])
+# => -ACT--IVE--ACT--IVE-
+#
+# | m4_foreach(Var, [[active], [active]], [-Var-])
+# => -ACT, IVE--ACT, IVE-
+#
+# | m4_foreach(Var, [[[active]], [[active]]], [-Var-])
+# => -active--active-
+#
+# This macro is called frequently, so avoid extra expansions such as
+# m4_ifval and dnl. Also, since $2 might be quite large, try to use it
+# as little as possible in _m4_foreach; each extra use requires that much
+# more memory for expansion. So, rather than directly compare $2 against
+# [] and use m4_car/m4_cdr for recursion, we instead unbox the list (which
+# requires swapping the argument order in the helper), insert an ignored
+# third argument, and use m4_shift3 to detect when recursion is complete.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_foreach],
+[m4_if([$2], [], [],
+ [m4_pushdef([$1])_$0([$1], [$3], [], $2)m4_popdef([$1])])])
+
+m4_define([_m4_foreach],
+[m4_if([$#], [3], [],
+ [m4_define([$1], [$4])$2[]$0([$1], [$2], m4_shift3($@))])])
+
+
+# m4_foreach_w(VARIABLE, LIST, EXPRESSION)
+# ----------------------------------------
+#
+# Like m4_foreach, but the list is whitespace separated.
+#
+# This macro is robust to active symbols:
+# m4_foreach_w([Var], [ active
+# b act\
+# ive ], [-Var-])end
+# => -active--b--active-end
+#
+m4_define([m4_foreach_w],
+[m4_foreach([$1], m4_split(m4_normalize([$2]), [ ]), [$3])])
+
+
+# m4_map(MACRO, LIST)
+# m4_mapall(MACRO, LIST)
+# ----------------------
+# Invoke MACRO($1), MACRO($2) etc. where $1, $2... are the elements of
+# LIST. $1, $2... must in turn be lists, appropriate for m4_apply.
+# If LIST contains an empty sublist, m4_map skips the expansion of
+# MACRO, while m4_mapall expands MACRO with no arguments.
+#
+# Since LIST may be quite large, we want to minimize how often it
+# appears in the expansion. Rather than use m4_car/m4_cdr iteration,
+# we unbox the list, ignore the second argument, and use m4_shift2 to
+# detect the end of recursion. The mismatch in () is intentional; see
+# _m4_map. For m4_map, an empty list behaves like an empty sublist
+# and gets ignored; for m4_mapall, we must special-case the empty
+# list.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_map],
+[_m4_map([_m4_apply([$1]], [], $2)])
+
+m4_define([m4_mapall],
+[m4_if([$2], [], [],
+ [_m4_map([m4_apply([$1]], [], $2)])])
+
+
+# m4_map_sep(MACRO, SEPARATOR, LIST)
+# m4_mapall_sep(MACRO, SEPARATOR, LIST)
+# -------------------------------------
+# Invoke MACRO($1), SEPARATOR, MACRO($2), ..., MACRO($N) where $1,
+# $2... $N are the elements of LIST, and are in turn lists appropriate
+# for m4_apply. SEPARATOR is expanded, in order to allow the creation
+# of a list of arguments by using a single-quoted comma as the
+# separator. For each empty sublist, m4_map_sep skips the expansion
+# of MACRO and SEPARATOR, while m4_mapall_sep expands MACRO with no
+# arguments.
+#
+# For m4_mapall_sep, merely expand the first iteration without the
+# separator, then include separator as part of subsequent recursion;
+# but avoid extra expansion of LIST's side-effects via a helper macro.
+# For m4_map_sep, things are trickier - we don't know if the first
+# list element is an empty sublist, so we must define a self-modifying
+# helper macro and use that as the separator instead.
+m4_define([m4_map_sep],
+[m4_pushdef([m4_Sep], [m4_define([m4_Sep], _m4_defn([m4_unquote]))])]dnl
+[_m4_map([_m4_apply([m4_Sep([$2])[]$1]], [], $3)m4_popdef([m4_Sep])])
+
+m4_define([m4_mapall_sep],
+[m4_if([$3], [], [], [_$0([$1], [$2], $3)])])
+
+m4_define([_m4_mapall_sep],
+[m4_apply([$1], [$3])_m4_map([m4_apply([$2[]$1]], m4_shift2($@))])
+
+# _m4_map(PREFIX, IGNORED, SUBLIST, ...)
+# --------------------------------------
+# Common implementation for all four m4_map variants. The mismatch in
+# the number of () is intentional. PREFIX must supply a form of
+# m4_apply, the open `(', and the MACRO to be applied. Each iteration
+# then appends `,', the current SUBLIST and the closing `)', then
+# recurses to the next SUBLIST. IGNORED is an aid to ending recursion
+# efficiently.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([_m4_map],
+[m4_if([$#], [2], [],
+ [$1, [$3])$0([$1], m4_shift2($@))])])
+
+# m4_transform(EXPRESSION, ARG...)
+# --------------------------------
+# Expand EXPRESSION([ARG]) for each argument. More efficient than
+# m4_foreach([var], [ARG...], [EXPRESSION(m4_defn([var]))])
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_transform],
+[m4_if([$#], [0], [m4_fatal([$0: too few arguments: $#])],
+ [$#], [1], [],
+ [$#], [2], [$1([$2])[]],
+ [$1([$2])[]$0([$1], m4_shift2($@))])])
+
+
+# m4_transform_pair(EXPRESSION, [END-EXPR = EXPRESSION], ARG...)
+# --------------------------------------------------------------
+# Perform a pairwise grouping of consecutive ARGs, by expanding
+# EXPRESSION([ARG1], [ARG2]). If there are an odd number of ARGs, the
+# final argument is expanded with END-EXPR([ARGn]).
+#
+# For example:
+# m4_define([show], [($*)m4_newline])dnl
+# m4_transform_pair([show], [], [a], [b], [c], [d], [e])dnl
+# => (a,b)
+# => (c,d)
+# => (e)
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_transform_pair],
+[m4_if([$#], [0], [m4_fatal([$0: too few arguments: $#])],
+ [$#], [1], [m4_fatal([$0: too few arguments: $#: $1])],
+ [$#], [2], [],
+ [$#], [3], [m4_default([$2], [$1])([$3])[]],
+ [$#], [4], [$1([$3], [$4])[]],
+ [$1([$3], [$4])[]$0([$1], [$2], m4_shift(m4_shift3($@)))])])
+
+
+## --------------------------- ##
+## 9. More diversion support. ##
+## --------------------------- ##
+
+
+# _m4_divert(DIVERSION-NAME or NUMBER)
+# ------------------------------------
+# If DIVERSION-NAME is the name of a diversion, return its number,
+# otherwise if it is a NUMBER return it.
+m4_define([_m4_divert],
+[m4_ifdef([_m4_divert($1)],
+ [m4_indir([_m4_divert($1)])],
+ [$1])])
+
+# KILL is only used to suppress output.
+m4_define([_m4_divert(KILL)], -1)
+
+# The empty diversion name is a synonym for 0.
+m4_define([_m4_divert()], 0)
+
+
+# _m4_divert_n_stack
+# ------------------
+# Print m4_divert_stack with newline prepended, if it's nonempty.
+m4_define([_m4_divert_n_stack],
+[m4_ifdef([m4_divert_stack], [
+_m4_defn([m4_divert_stack])])])
+
+
+# m4_divert(DIVERSION-NAME)
+# -------------------------
+# Change the diversion stream to DIVERSION-NAME.
+m4_define([m4_divert],
+[m4_define([m4_divert_stack], m4_location[: $0: $1]_m4_divert_n_stack)]dnl
+[m4_builtin([divert], _m4_divert([$1]))])
+
+
+# m4_divert_push(DIVERSION-NAME)
+# ------------------------------
+# Change the diversion stream to DIVERSION-NAME, while stacking old values.
+m4_define([m4_divert_push],
+[m4_pushdef([m4_divert_stack], m4_location[: $0: $1]_m4_divert_n_stack)]dnl
+[m4_pushdef([_m4_divert_diversion], [$1])]dnl
+[m4_builtin([divert], _m4_divert([$1]))])
+
+
+# m4_divert_pop([DIVERSION-NAME])
+# -------------------------------
+# Change the diversion stream to its previous value, unstacking it.
+# If specified, verify we left DIVERSION-NAME.
+# When we pop the last value from the stack, we divert to -1.
+m4_define([m4_divert_pop],
+[m4_ifndef([_m4_divert_diversion],
+ [m4_fatal([too many m4_divert_pop])])]dnl
+[m4_if([$1], [], [],
+ [$1], _m4_defn([_m4_divert_diversion]), [],
+ [m4_fatal([$0($1): diversion mismatch: ]_m4_divert_n_stack)])]dnl
+[_m4_popdef([m4_divert_stack], [_m4_divert_diversion])]dnl
+[m4_builtin([divert],
+ m4_ifdef([_m4_divert_diversion],
+ [_m4_divert(_m4_defn([_m4_divert_diversion]))],
+ -1))])
+
+
+# m4_divert_text(DIVERSION-NAME, CONTENT)
+# ---------------------------------------
+# Output CONTENT into DIVERSION-NAME (which may be a number actually).
+# An end of line is appended for free to CONTENT.
+m4_define([m4_divert_text],
+[m4_divert_push([$1])$2
+m4_divert_pop([$1])])
+
+
+# m4_divert_once(DIVERSION-NAME, CONTENT)
+# ---------------------------------------
+# Output CONTENT into DIVERSION-NAME once, if not already there.
+# An end of line is appended for free to CONTENT.
+m4_define([m4_divert_once],
+[m4_expand_once([m4_divert_text([$1], [$2])])])
+
+
+# m4_undivert(DIVERSION-NAME)
+# ---------------------------
+# Undivert DIVERSION-NAME. Unlike the M4 version, this only takes a single
+# diversion identifier, and should not be used to undivert files.
+m4_define([m4_undivert],
+[m4_builtin([undivert], _m4_divert([$1]))])
+
+
+## --------------------------------------------- ##
+## 10. Defining macros with bells and whistles. ##
+## --------------------------------------------- ##
+
+# `m4_defun' is basically `m4_define' but it equips the macro with the
+# needed machinery for `m4_require'. A macro must be m4_defun'd if
+# either it is m4_require'd, or it m4_require's.
+#
+# Two things deserve attention and are detailed below:
+# 1. Implementation of m4_require
+# 2. Keeping track of the expansion stack
+#
+# 1. Implementation of m4_require
+# ===============================
+#
+# Of course m4_defun AC_PROVIDE's the macro, so that a macro which has
+# been expanded is not expanded again when m4_require'd, but the
+# difficult part is the proper expansion of macros when they are
+# m4_require'd.
+#
+# The implementation is based on two ideas, (i) using diversions to
+# prepare the expansion of the macro and its dependencies (by Franc,ois
+# Pinard), and (ii) expand the most recently m4_require'd macros _after_
+# the previous macros (by Axel Thimm).
+#
+#
+# The first idea: why use diversions?
+# -----------------------------------
+#
+# When a macro requires another, the other macro is expanded in new
+# diversion, GROW. When the outer macro is fully expanded, we first
+# undivert the most nested diversions (GROW - 1...), and finally
+# undivert GROW. To understand why we need several diversions,
+# consider the following example:
+#
+# | m4_defun([TEST1], [Test...REQUIRE([TEST2])1])
+# | m4_defun([TEST2], [Test...REQUIRE([TEST3])2])
+# | m4_defun([TEST3], [Test...3])
+#
+# Because m4_require is not required to be first in the outer macros, we
+# must keep the expansions of the various levels of m4_require separated.
+# Right before executing the epilogue of TEST1, we have:
+#
+# GROW - 2: Test...3
+# GROW - 1: Test...2
+# GROW: Test...1
+# BODY:
+#
+# Finally the epilogue of TEST1 undiverts GROW - 2, GROW - 1, and
+# GROW into the regular flow, BODY.
+#
+# GROW - 2:
+# GROW - 1:
+# GROW:
+# BODY: Test...3; Test...2; Test...1
+#
+# (The semicolons are here for clarification, but of course are not
+# emitted.) This is what Autoconf 2.0 (I think) to 2.13 (I'm sure)
+# implement.
+#
+#
+# The second idea: first required first out
+# -----------------------------------------
+#
+# The natural implementation of the idea above is buggy and produces
+# very surprising results in some situations. Let's consider the
+# following example to explain the bug:
+#
+# | m4_defun([TEST1], [REQUIRE([TEST2a])REQUIRE([TEST2b])])
+# | m4_defun([TEST2a], [])
+# | m4_defun([TEST2b], [REQUIRE([TEST3])])
+# | m4_defun([TEST3], [REQUIRE([TEST2a])])
+# |
+# | AC_INIT
+# | TEST1
+#
+# The dependencies between the macros are:
+#
+# 3 --- 2b
+# / \ is m4_require'd by
+# / \ left -------------------- right
+# 2a ------------ 1
+#
+# If you strictly apply the rules given in the previous section you get:
+#
+# GROW - 2: TEST3
+# GROW - 1: TEST2a; TEST2b
+# GROW: TEST1
+# BODY:
+#
+# (TEST2a, although required by TEST3 is not expanded in GROW - 3
+# because is has already been expanded before in GROW - 1, so it has
+# been AC_PROVIDE'd, so it is not expanded again) so when you undivert
+# the stack of diversions, you get:
+#
+# GROW - 2:
+# GROW - 1:
+# GROW:
+# BODY: TEST3; TEST2a; TEST2b; TEST1
+#
+# i.e., TEST2a is expanded after TEST3 although the latter required the
+# former.
+#
+# Starting from 2.50, we use an implementation provided by Axel Thimm.
+# The idea is simple: the order in which macros are emitted must be the
+# same as the one in which macros are expanded. (The bug above can
+# indeed be described as: a macro has been AC_PROVIDE'd before its
+# dependent, but it is emitted after: the lack of correlation between
+# emission and expansion order is guilty).
+#
+# How to do that? You keep the stack of diversions to elaborate the
+# macros, but each time a macro is fully expanded, emit it immediately.
+#
+# In the example above, when TEST2a is expanded, but it's epilogue is
+# not run yet, you have:
+#
+# GROW - 2:
+# GROW - 1: TEST2a
+# GROW: Elaboration of TEST1
+# BODY:
+#
+# The epilogue of TEST2a emits it immediately:
+#
+# GROW - 2:
+# GROW - 1:
+# GROW: Elaboration of TEST1
+# BODY: TEST2a
+#
+# TEST2b then requires TEST3, so right before the epilogue of TEST3, you
+# have:
+#
+# GROW - 2: TEST3
+# GROW - 1: Elaboration of TEST2b
+# GROW: Elaboration of TEST1
+# BODY: TEST2a
+#
+# The epilogue of TEST3 emits it:
+#
+# GROW - 2:
+# GROW - 1: Elaboration of TEST2b
+# GROW: Elaboration of TEST1
+# BODY: TEST2a; TEST3
+#
+# TEST2b is now completely expanded, and emitted:
+#
+# GROW - 2:
+# GROW - 1:
+# GROW: Elaboration of TEST1
+# BODY: TEST2a; TEST3; TEST2b
+#
+# and finally, TEST1 is finished and emitted:
+#
+# GROW - 2:
+# GROW - 1:
+# GROW:
+# BODY: TEST2a; TEST3; TEST2b: TEST1
+#
+# The idea is simple, but the implementation is a bit evolved. If you
+# are like me, you will want to see the actual functioning of this
+# implementation to be convinced. The next section gives the full
+# details.
+#
+#
+# The Axel Thimm implementation at work
+# -------------------------------------
+#
+# We consider the macros above, and this configure.ac:
+#
+# AC_INIT
+# TEST1
+#
+# You should keep the definitions of _m4_defun_pro, _m4_defun_epi, and
+# m4_require at hand to follow the steps.
+#
+# This implements tries not to assume that the current diversion is
+# BODY, so as soon as a macro (m4_defun'd) is expanded, we first
+# record the current diversion under the name _m4_divert_dump (denoted
+# DUMP below for short). This introduces an important difference with
+# the previous versions of Autoconf: you cannot use m4_require if you
+# are not inside an m4_defun'd macro, and especially, you cannot
+# m4_require directly from the top level.
+#
+# We have not tried to simulate the old behavior (better yet, we
+# diagnose it), because it is too dangerous: a macro m4_require'd from
+# the top level is expanded before the body of `configure', i.e., before
+# any other test was run. I let you imagine the result of requiring
+# AC_STDC_HEADERS for instance, before AC_PROG_CC was actually run....
+#
+# After AC_INIT was run, the current diversion is BODY.
+# * AC_INIT was run
+# DUMP: undefined
+# diversion stack: BODY |-
+#
+# * TEST1 is expanded
+# The prologue of TEST1 sets _m4_divert_dump, which is the diversion
+# where the current elaboration will be dumped, to the current
+# diversion. It also m4_divert_push to GROW, where the full
+# expansion of TEST1 and its dependencies will be elaborated.
+# DUMP: BODY
+# BODY: empty
+# diversions: GROW, BODY |-
+#
+# * TEST1 requires TEST2a
+# _m4_require_call m4_divert_pushes another temporary diversion,
+# GROW - 1, and expands TEST2a in there.
+# DUMP: BODY
+# BODY: empty
+# GROW - 1: TEST2a
+# diversions: GROW - 1, GROW, BODY |-
+# Than the content of the temporary diversion is moved to DUMP and the
+# temporary diversion is popped.
+# DUMP: BODY
+# BODY: TEST2a
+# diversions: GROW, BODY |-
+#
+# * TEST1 requires TEST2b
+# Again, _m4_require_call pushes GROW - 1 and heads to expand TEST2b.
+# DUMP: BODY
+# BODY: TEST2a
+# diversions: GROW - 1, GROW, BODY |-
+#
+# * TEST2b requires TEST3
+# _m4_require_call pushes GROW - 2 and expands TEST3 here.
+# (TEST3 requires TEST2a, but TEST2a has already been m4_provide'd, so
+# nothing happens.)
+# DUMP: BODY
+# BODY: TEST2a
+# GROW - 2: TEST3
+# diversions: GROW - 2, GROW - 1, GROW, BODY |-
+# Than the diversion is appended to DUMP, and popped.
+# DUMP: BODY
+# BODY: TEST2a; TEST3
+# diversions: GROW - 1, GROW, BODY |-
+#
+# * TEST1 requires TEST2b (contd.)
+# The content of TEST2b is expanded...
+# DUMP: BODY
+# BODY: TEST2a; TEST3
+# GROW - 1: TEST2b,
+# diversions: GROW - 1, GROW, BODY |-
+# ... and moved to DUMP.
+# DUMP: BODY
+# BODY: TEST2a; TEST3; TEST2b
+# diversions: GROW, BODY |-
+#
+# * TEST1 is expanded: epilogue
+# TEST1's own content is in GROW...
+# DUMP: BODY
+# BODY: TEST2a; TEST3; TEST2b
+# GROW: TEST1
+# diversions: BODY |-
+# ... and it's epilogue moves it to DUMP and then undefines DUMP.
+# DUMP: undefined
+# BODY: TEST2a; TEST3; TEST2b; TEST1
+# diversions: BODY |-
+#
+#
+# 2. Keeping track of the expansion stack
+# =======================================
+#
+# When M4 expansion goes wrong it is often extremely hard to find the
+# path amongst macros that drove to the failure. What is needed is
+# the stack of macro `calls'. One could imagine that GNU M4 would
+# maintain a stack of macro expansions, unfortunately it doesn't, so
+# we do it by hand. This is of course extremely costly, but the help
+# this stack provides is worth it. Nevertheless to limit the
+# performance penalty this is implemented only for m4_defun'd macros,
+# not for define'd macros.
+#
+# The scheme is simplistic: each time we enter an m4_defun'd macros,
+# we prepend its name in m4_expansion_stack, and when we exit the
+# macro, we remove it (thanks to pushdef/popdef).
+#
+# In addition, we want to detect circular m4_require dependencies.
+# Each time we expand a macro FOO we define _m4_expanding(FOO); and
+# m4_require(BAR) simply checks whether _m4_expanding(BAR) is defined.
+
+
+# m4_expansion_stack_push(TEXT)
+# -----------------------------
+m4_define([m4_expansion_stack_push],
+[m4_pushdef([m4_expansion_stack],
+ [$1]m4_ifdef([m4_expansion_stack], [
+_m4_defn([m4_expansion_stack])]))])
+
+
+# m4_expansion_stack_pop
+# ----------------------
+m4_define([m4_expansion_stack_pop],
+[m4_popdef([m4_expansion_stack])])
+
+
+# m4_expansion_stack_dump
+# -----------------------
+# Dump the expansion stack.
+m4_define([m4_expansion_stack_dump],
+[m4_ifdef([m4_expansion_stack],
+ [m4_errprintn(_m4_defn([m4_expansion_stack]))])dnl
+m4_errprintn(m4_location[: the top level])])
+
+
+# _m4_divert(GROW)
+# ----------------
+# This diversion is used by the m4_defun/m4_require machinery. It is
+# important to keep room before GROW because for each nested
+# AC_REQUIRE we use an additional diversion (i.e., two m4_require's
+# will use GROW - 2. More than 3 levels has never seemed to be
+# needed.)
+#
+# ...
+# - GROW - 2
+# m4_require'd code, 2 level deep
+# - GROW - 1
+# m4_require'd code, 1 level deep
+# - GROW
+# m4_defun'd macros are elaborated here.
+
+m4_define([_m4_divert(GROW)], 10000)
+
+
+# _m4_defun_pro(MACRO-NAME)
+# -------------------------
+# The prologue for Autoconf macros.
+#
+# This is called frequently, so minimize the number of macro invocations
+# by avoiding dnl and m4_defn overhead.
+m4_define([_m4_defun_pro],
+m4_do([[m4_ifdef([m4_expansion_stack], [], [_m4_defun_pro_outer[]])]],
+ [[m4_expansion_stack_push(_m4_defn(
+ [m4_location($1)])[: $1 is expanded from...])]],
+ [[m4_pushdef([_m4_expanding($1)])]]))
+
+m4_define([_m4_defun_pro_outer],
+[m4_copy([_m4_divert_diversion], [_m4_divert_dump])m4_divert_push([GROW])])
+
+# _m4_defun_epi(MACRO-NAME)
+# -------------------------
+# The Epilogue for Autoconf macros. MACRO-NAME only helps tracing
+# the PRO/EPI pairs.
+#
+# This is called frequently, so minimize the number of macro invocations
+# by avoiding dnl and m4_popdef overhead.
+m4_define([_m4_defun_epi],
+m4_do([[_m4_popdef([_m4_expanding($1)])]],
+ [[m4_expansion_stack_pop()]],
+ [[m4_ifdef([m4_expansion_stack], [], [_m4_defun_epi_outer[]])]],
+ [[m4_provide([$1])]]))
+
+m4_define([_m4_defun_epi_outer],
+[_m4_undefine([_m4_divert_dump])m4_divert_pop([GROW])m4_undivert([GROW])])
+
+
+# m4_defun(NAME, EXPANSION)
+# -------------------------
+# Define a macro which automatically provides itself. Add machinery
+# so the macro automatically switches expansion to the diversion
+# stack if it is not already using it. In this case, once finished,
+# it will bring back all the code accumulated in the diversion stack.
+# This, combined with m4_require, achieves the topological ordering of
+# macros. We don't use this macro to define some frequently called
+# macros that are not involved in ordering constraints, to save m4
+# processing.
+m4_define([m4_defun],
+[m4_define([m4_location($1)], m4_location)dnl
+m4_define([$1],
+ [_m4_defun_pro([$1])$2[]_m4_defun_epi([$1])])])
+
+
+# m4_defun_once(NAME, EXPANSION)
+# ------------------------------
+# As m4_defun, but issues the EXPANSION only once, and warns if used
+# several times.
+m4_define([m4_defun_once],
+[m4_define([m4_location($1)], m4_location)dnl
+m4_define([$1],
+ [m4_provide_if([$1],
+ [m4_warn([syntax], [$1 invoked multiple times])],
+ [_m4_defun_pro([$1])$2[]_m4_defun_epi([$1])])])])
+
+
+# m4_pattern_forbid(ERE, [WHY])
+# -----------------------------
+# Declare that no token matching the forbidden extended regular
+# expression ERE should be seen in the output unless...
+m4_define([m4_pattern_forbid], [])
+
+
+# m4_pattern_allow(ERE)
+# ---------------------
+# ... that token also matches the allowed extended regular expression ERE.
+# Both used via traces.
+m4_define([m4_pattern_allow], [])
+
+
+## --------------------------------- ##
+## 11. Dependencies between macros. ##
+## --------------------------------- ##
+
+
+# m4_before(THIS-MACRO-NAME, CALLED-MACRO-NAME)
+# ---------------------------------------------
+# Issue a warning if CALLED-MACRO-NAME was called before THIS-MACRO-NAME.
+m4_define([m4_before],
+[m4_provide_if([$2],
+ [m4_warn([syntax], [$2 was called before $1])])])
+
+
+# m4_require(NAME-TO-CHECK, [BODY-TO-EXPAND = NAME-TO-CHECK])
+# -----------------------------------------------------------
+# If NAME-TO-CHECK has never been expanded (actually, if it is not
+# m4_provide'd), expand BODY-TO-EXPAND *before* the current macro
+# expansion. Once expanded, emit it in _m4_divert_dump. Keep track
+# of the m4_require chain in m4_expansion_stack.
+#
+# The normal cases are:
+#
+# - NAME-TO-CHECK == BODY-TO-EXPAND
+# Which you can use for regular macros with or without arguments, e.g.,
+# m4_require([AC_PROG_CC], [AC_PROG_CC])
+# m4_require([AC_CHECK_HEADERS(limits.h)], [AC_CHECK_HEADERS(limits.h)])
+# which is just the same as
+# m4_require([AC_PROG_CC])
+# m4_require([AC_CHECK_HEADERS(limits.h)])
+#
+# - BODY-TO-EXPAND == m4_indir([NAME-TO-CHECK])
+# In the case of macros with irregular names. For instance:
+# m4_require([AC_LANG_COMPILER(C)], [indir([AC_LANG_COMPILER(C)])])
+# which means `if the macro named `AC_LANG_COMPILER(C)' (the parens are
+# part of the name, it is not an argument) has not been run, then
+# call it.'
+# Had you used
+# m4_require([AC_LANG_COMPILER(C)], [AC_LANG_COMPILER(C)])
+# then m4_require would have tried to expand `AC_LANG_COMPILER(C)', i.e.,
+# call the macro `AC_LANG_COMPILER' with `C' as argument.
+#
+# You could argue that `AC_LANG_COMPILER', when it receives an argument
+# such as `C' should dispatch the call to `AC_LANG_COMPILER(C)'. But this
+# `extension' prevents `AC_LANG_COMPILER' from having actual arguments that
+# it passes to `AC_LANG_COMPILER(C)'.
+#
+# This is called frequently, so minimize the number of macro invocations
+# by avoiding dnl and other overhead on the common path.
+m4_define([m4_require],
+m4_do([[m4_ifdef([_m4_expanding($1)],
+ [m4_fatal([$0: circular dependency of $1])])]],
+ [[m4_ifdef([_m4_divert_dump], [],
+ [m4_fatal([$0($1): cannot be used outside of an ]dnl
+m4_bmatch([$0], [^AC_], [[AC_DEFUN]], [[m4_defun]])['d macro])])]],
+ [[m4_provide_if([$1],
+ [],
+ [_m4_require_call([$1], [$2])])]]))
+
+
+# _m4_require_call(NAME-TO-CHECK, [BODY-TO-EXPAND = NAME-TO-CHECK])
+# -----------------------------------------------------------------
+# If m4_require decides to expand the body, it calls this macro.
+#
+# This is called frequently, so minimize the number of macro invocations
+# by avoiding dnl and other overhead on the common path.
+m4_define([_m4_require_call],
+m4_do([[m4_define([_m4_divert_grow], m4_decr(_m4_divert_grow))]],
+ [[m4_divert_push(_m4_divert_grow)]],
+ [[m4_default([$2], [$1])
+m4_provide_if([$1],
+ [],
+ [m4_warn([syntax],
+ [$1 is m4_require'd but not m4_defun'd])])]],
+ [[m4_divert(_m4_defn([_m4_divert_dump]))]],
+ [[m4_undivert(_m4_divert_grow)]],
+ [[m4_divert_pop(_m4_divert_grow)]],
+ [[m4_define([_m4_divert_grow], m4_incr(_m4_divert_grow))]]))
+
+
+# _m4_divert_grow
+# ---------------
+# The counter for _m4_require_call.
+m4_define([_m4_divert_grow], _m4_divert([GROW]))
+
+
+# m4_expand_once(TEXT, [WITNESS = TEXT])
+# --------------------------------------
+# If TEXT has never been expanded, expand it *here*. Use WITNESS as
+# as a memory that TEXT has already been expanded.
+m4_define([m4_expand_once],
+[m4_provide_if(m4_ifval([$2], [[$2]], [[$1]]),
+ [],
+ [m4_provide(m4_ifval([$2], [[$2]], [[$1]]))[]$1])])
+
+
+# m4_provide(MACRO-NAME)
+# ----------------------
+m4_define([m4_provide],
+[m4_define([m4_provide($1)])])
+
+
+# m4_provide_if(MACRO-NAME, IF-PROVIDED, IF-NOT-PROVIDED)
+# -------------------------------------------------------
+# If MACRO-NAME is provided do IF-PROVIDED, else IF-NOT-PROVIDED.
+# The purpose of this macro is to provide the user with a means to
+# check macros which are provided without letting her know how the
+# information is coded.
+m4_define([m4_provide_if],
+[m4_ifdef([m4_provide($1)],
+ [$2], [$3])])
+
+
+## --------------------- ##
+## 12. Text processing. ##
+## --------------------- ##
+
+
+# m4_cr_letters
+# m4_cr_LETTERS
+# m4_cr_Letters
+# -------------
+m4_define([m4_cr_letters], [abcdefghijklmnopqrstuvwxyz])
+m4_define([m4_cr_LETTERS], [ABCDEFGHIJKLMNOPQRSTUVWXYZ])
+m4_define([m4_cr_Letters],
+m4_defn([m4_cr_letters])dnl
+m4_defn([m4_cr_LETTERS])dnl
+)
+
+
+# m4_cr_digits
+# ------------
+m4_define([m4_cr_digits], [0123456789])
+
+
+# m4_cr_alnum
+# -----------
+m4_define([m4_cr_alnum],
+m4_defn([m4_cr_Letters])dnl
+m4_defn([m4_cr_digits])dnl
+)
+
+
+# m4_cr_symbols1
+# m4_cr_symbols2
+# -------------------------------
+m4_define([m4_cr_symbols1],
+m4_defn([m4_cr_Letters])dnl
+_)
+
+m4_define([m4_cr_symbols2],
+m4_defn([m4_cr_symbols1])dnl
+m4_defn([m4_cr_digits])dnl
+)
+
+# m4_cr_all
+# ---------
+# The character range representing everything, with `-' as the last
+# character, since it is special to m4_translit. Use with care, because
+# it contains characters special to M4 (fortunately, both ASCII and EBCDIC
+# have [] in order, so m4_defn([m4_cr_all]) remains a valid string). It
+# also contains characters special to terminals, so it should never be
+# displayed in an error message. Also, attempts to map [ and ] to other
+# characters via m4_translit must deal with the fact that m4_translit does
+# not add quotes to the output.
+#
+# It is mainly useful in generating inverted character range maps, for use
+# in places where m4_translit is faster than an equivalent m4_bpatsubst;
+# the regex `[^a-z]' is equivalent to:
+# m4_translit(m4_dquote(m4_defn([m4_cr_all])), [a-z])
+m4_define([m4_cr_all],
+m4_translit(m4_dquote(m4_format(m4_dquote(m4_for(
+ ,1,255,,[[%c]]))m4_for([i],1,255,,[,i]))), [-])-)
+
+
+# _m4_define_cr_not(CATEGORY)
+# ---------------------------
+# Define m4_cr_not_CATEGORY as the inverse of m4_cr_CATEGORY.
+m4_define([_m4_define_cr_not],
+[m4_define([m4_cr_not_$1],
+ m4_translit(m4_dquote(m4_defn([m4_cr_all])),
+ m4_defn([m4_cr_$1])))])
+
+
+# m4_cr_not_letters
+# m4_cr_not_LETTERS
+# m4_cr_not_Letters
+# m4_cr_not_digits
+# m4_cr_not_alnum
+# m4_cr_not_symbols1
+# m4_cr_not_symbols2
+# ------------------
+# Inverse character sets
+_m4_define_cr_not([letters])
+_m4_define_cr_not([LETTERS])
+_m4_define_cr_not([Letters])
+_m4_define_cr_not([digits])
+_m4_define_cr_not([alnum])
+_m4_define_cr_not([symbols1])
+_m4_define_cr_not([symbols2])
+
+
+# m4_newline
+# ----------
+# Expands to a newline. Exists for formatting reasons.
+m4_define([m4_newline], [
+])
+
+
+# m4_re_escape(STRING)
+# --------------------
+# Escape RE active characters in STRING.
+m4_define([m4_re_escape],
+[m4_bpatsubst([$1],
+ [[][*+.?\^$]], [\\\&])])
+
+
+# m4_re_string
+# ------------
+# Regexp for `[a-zA-Z_0-9]*'
+# m4_dquote provides literal [] for the character class.
+m4_define([m4_re_string],
+m4_dquote(m4_defn([m4_cr_symbols2]))dnl
+[*]dnl
+)
+
+
+# m4_re_word
+# ----------
+# Regexp for `[a-zA-Z_][a-zA-Z_0-9]*'
+m4_define([m4_re_word],
+m4_dquote(m4_defn([m4_cr_symbols1]))dnl
+m4_defn([m4_re_string])dnl
+)
+
+
+# m4_tolower(STRING)
+# m4_toupper(STRING)
+# ------------------
+# These macros convert STRING to lowercase or uppercase.
+#
+# Rather than expand the m4_defn each time, we inline them up front.
+m4_define([m4_tolower],
+[m4_translit([$1], ]m4_dquote(m4_defn([m4_cr_LETTERS]))[,
+ ]m4_dquote(m4_defn([m4_cr_letters]))[)])
+m4_define([m4_toupper],
+[m4_translit([$1], ]m4_dquote(m4_defn([m4_cr_letters]))[,
+ ]m4_dquote(m4_defn([m4_cr_LETTERS]))[)])
+
+
+# m4_split(STRING, [REGEXP])
+# --------------------------
+#
+# Split STRING into an m4 list of quoted elements. The elements are
+# quoted with [ and ]. Beginning spaces and end spaces *are kept*.
+# Use m4_strip to remove them.
+#
+# REGEXP specifies where to split. Default is [\t ]+.
+#
+# If STRING is empty, the result is an empty list.
+#
+# Pay attention to the m4_changequotes. When m4 reads the definition of
+# m4_split, it still has quotes set to [ and ]. Luckily, these are matched
+# in the macro body, so the definition is stored correctly. Use the same
+# alternate quotes as m4_noquote; it must be unlikely to appear in $1.
+#
+# Also, notice that $1 is quoted twice, since we want the result to
+# be quoted. Then you should understand that the argument of
+# patsubst is -=<{(STRING)}>=- (i.e., with additional -=<{( and )}>=-).
+#
+# This macro is safe on active symbols, i.e.:
+# m4_define(active, ACTIVE)
+# m4_split([active active ])end
+# => [active], [active], []end
+#
+# Optimize on regex of ` ' (space), since m4_foreach_w already guarantees
+# that the list contains single space separators, and a common case is
+# splitting a single-element list. This macro is called frequently,
+# so avoid unnecessary dnl inside the definition.
+m4_define([m4_split],
+[m4_if([$1], [], [],
+ [$2], [ ], [m4_if(m4_index([$1], [ ]), [-1], [[[$1]]], [_$0($@)])],
+ [$2], [], [_$0([$1], [[ ]+])],
+ [_$0($@)])])
+
+m4_define([_m4_split],
+[m4_changequote([-=<{(],[)}>=-])]dnl
+[[m4_bpatsubst(-=<{(-=<{($1)}>=-)}>=-, -=<{($2)}>=-,
+ -=<{(], [)}>=-)]m4_changequote([, ])])
+
+
+
+# m4_flatten(STRING)
+# ------------------
+# If STRING contains end of lines, replace them with spaces. If there
+# are backslashed end of lines, remove them. This macro is safe with
+# active symbols.
+# m4_define(active, ACTIVE)
+# m4_flatten([active
+# act\
+# ive])end
+# => active activeend
+#
+# In m4, m4_bpatsubst is expensive, so first check for a newline.
+m4_define([m4_flatten],
+[m4_if(m4_index([$1], [
+]), [-1], [[$1]],
+ [m4_translit(m4_bpatsubst([[[$1]]], [\\
+]), [
+], [ ])])])
+
+
+# m4_strip(STRING)
+# ----------------
+# Expands into STRING with tabs and spaces singled out into a single
+# space, and removing leading and trailing spaces.
+#
+# This macro is robust to active symbols.
+# m4_define(active, ACTIVE)
+# m4_strip([ active <tab> <tab>active ])end
+# => active activeend
+#
+# First, notice that we guarantee trailing space. Why? Because regular
+# expressions are greedy, and `.* ?' would always group the space into the
+# .* portion. The algorithm is simpler by avoiding `?' at the end. The
+# algorithm correctly strips everything if STRING is just ` '.
+#
+# Then notice the second pattern: it is in charge of removing the
+# leading/trailing spaces. Why not just `[^ ]'? Because they are
+# applied to over-quoted strings, i.e. more or less [STRING], due
+# to the limitations of m4_bpatsubsts. So the leading space in STRING
+# is the *second* character; equally for the trailing space.
+m4_define([m4_strip],
+[m4_bpatsubsts([$1 ],
+ [[ ]+], [ ],
+ [^. ?\(.*\) .$], [[[\1]]])])
+
+
+# m4_normalize(STRING)
+# --------------------
+# Apply m4_flatten and m4_strip to STRING.
+#
+# The argument is quoted, so that the macro is robust to active symbols:
+#
+# m4_define(active, ACTIVE)
+# m4_normalize([ act\
+# ive
+# active ])end
+# => active activeend
+
+m4_define([m4_normalize],
+[m4_strip(m4_flatten([$1]))])
+
+
+
+# m4_join(SEP, ARG1, ARG2...)
+# ---------------------------
+# Produce ARG1SEPARG2...SEPARGn. Avoid back-to-back SEP when a given ARG
+# is the empty string. No expansion is performed on SEP or ARGs.
+#
+# Since the number of arguments to join can be arbitrarily long, we
+# want to avoid having more than one $@ in the macro definition;
+# otherwise, the expansion would require twice the memory of the already
+# long list. Hence, m4_join merely looks for the first non-empty element,
+# and outputs just that element; while _m4_join looks for all non-empty
+# elements, and outputs them following a separator. The final trick to
+# note is that we decide between recursing with $0 or _$0 based on the
+# nested m4_if ending with `_'.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_join],
+[m4_if([$#], [1], [],
+ [$#], [2], [[$2]],
+ [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift2($@))])])
+m4_define([_m4_join],
+[m4_if([$#$2], [2], [],
+ [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift2($@))])])
+
+# m4_joinall(SEP, ARG1, ARG2...)
+# ------------------------------
+# Produce ARG1SEPARG2...SEPARGn. An empty ARG results in back-to-back SEP.
+# No expansion is performed on SEP or ARGs.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_joinall], [[$2]_$0([$1], m4_shift($@))])
+m4_define([_m4_joinall],
+[m4_if([$#], [2], [], [[$1$3]$0([$1], m4_shift2($@))])])
+
+# m4_combine([SEPARATOR], PREFIX-LIST, [INFIX], SUFFIX...)
+# --------------------------------------------------------
+# Produce the pairwise combination of every element in the quoted,
+# comma-separated PREFIX-LIST with every element from the SUFFIX arguments.
+# Each pair is joined with INFIX, and pairs are separated by SEPARATOR.
+# No expansion occurs on SEPARATOR, INFIX, or elements of either list.
+#
+# For example:
+# m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
+# => a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
+#
+# In order to have the correct number of SEPARATORs, we use a temporary
+# variable that redefines itself after the first use. We must use defn
+# rather than overquoting in case PREFIX or SUFFIX contains $1, but use
+# _m4_defn for speed. Likewise, we compute the m4_shift3 only once,
+# rather than in each iteration of the outer m4_foreach.
+m4_define([m4_combine],
+[m4_if(m4_eval([$# > 3]), [1],
+ [m4_pushdef([m4_Separator], [m4_define([m4_Separator],
+ _m4_defn([m4_echo]))])]]dnl
+[[m4_foreach([m4_Prefix], [$2],
+ [m4_foreach([m4_Suffix], ]m4_dquote(m4_dquote(m4_shift3($@)))[,
+ [m4_Separator([$1])[]_m4_defn([m4_Prefix])[$3]_m4_defn(
+ [m4_Suffix])])])]]dnl
+[[_m4_popdef([m4_Separator])])])
+
+
+# m4_append(MACRO-NAME, STRING, [SEPARATOR])
+# ------------------------------------------
+# Redefine MACRO-NAME to hold its former content plus `SEPARATOR`'STRING'
+# at the end. It is valid to use this macro with MACRO-NAME undefined,
+# in which case no SEPARATOR is added. Be aware that the criterion is
+# `not being defined', and not `not being empty'.
+#
+# Note that neither STRING nor SEPARATOR are expanded here; rather, when
+# you expand MACRO-NAME, they will be expanded at that point in time.
+#
+# This macro is robust to active symbols. It can be used to grow
+# strings.
+#
+# | m4_define(active, ACTIVE)dnl
+# | m4_append([sentence], [This is an])dnl
+# | m4_append([sentence], [ active ])dnl
+# | m4_append([sentence], [symbol.])dnl
+# | sentence
+# | m4_undefine([active])dnl
+# | sentence
+# => This is an ACTIVE symbol.
+# => This is an active symbol.
+#
+# It can be used to define hooks.
+#
+# | m4_define(active, ACTIVE)dnl
+# | m4_append([hooks], [m4_define([act1], [act2])])dnl
+# | m4_append([hooks], [m4_define([act2], [active])])dnl
+# | m4_undefine([active])dnl
+# | act1
+# | hooks
+# | act1
+# => act1
+# =>
+# => active
+#
+# It can also be used to create lists, although this particular usage was
+# broken prior to autoconf 2.62.
+# | m4_append([list], [one], [, ])dnl
+# | m4_append([list], [two], [, ])dnl
+# | m4_append([list], [three], [, ])dnl
+# | list
+# | m4_dquote(list)
+# => one, two, three
+# => [one],[two],[three]
+#
+# Note that m4_append can benefit from amortized O(n) m4 behavior, if
+# the underlying m4 implementation is smart enough to avoid copying existing
+# contents when enlarging a macro's definition into any pre-allocated storage
+# (m4 1.4.x unfortunately does not implement this optimization). We do
+# not implement m4_prepend, since it is inherently O(n^2) (pre-allocated
+# storage only occurs at the end of a macro, so the existing contents must
+# always be moved).
+#
+# Use _m4_defn for speed.
+m4_define([m4_append],
+[m4_define([$1], m4_ifdef([$1], [_m4_defn([$1])[$3]])[$2])])
+
+
+# m4_append_uniq(MACRO-NAME, STRING, [SEPARATOR], [IF-UNIQ], [IF-DUP])
+# --------------------------------------------------------------------
+# Like `m4_append', but append only if not yet present. Additionally,
+# expand IF-UNIQ if STRING was appended, or IF-DUP if STRING was already
+# present. Also, warn if SEPARATOR is not empty and occurs within STRING,
+# as the algorithm no longer guarantees uniqueness.
+#
+# Note that while m4_append can be O(n) (depending on the quality of the
+# underlying M4 implementation), m4_append_uniq is inherently O(n^2)
+# because each append operation searches the entire string.
+m4_define([m4_append_uniq],
+[m4_ifval([$3], [m4_if(m4_index([$2], [$3]), [-1], [],
+ [m4_warn([syntax],
+ [$0: `$2' contains `$3'])])])_$0($@)])
+m4_define([_m4_append_uniq],
+[m4_ifdef([$1],
+ [m4_if(m4_index([$3]_m4_defn([$1])[$3], [$3$2$3]), [-1],
+ [m4_append([$1], [$2], [$3])$4], [$5])],
+ [m4_define([$1], [$2])$4])])
+
+# m4_append_uniq_w(MACRO-NAME, STRINGS)
+# -------------------------------------
+# For each of the words in the whitespace separated list STRINGS, append
+# only the unique strings to the definition of MACRO-NAME.
+#
+# Use _m4_defn for speed.
+m4_define([m4_append_uniq_w],
+[m4_foreach_w([m4_Word], [$2],
+ [_m4_append_uniq([$1], _m4_defn([m4_Word]), [ ])])])
+
+
+# m4_text_wrap(STRING, [PREFIX], [FIRST-PREFIX], [WIDTH])
+# -------------------------------------------------------
+# Expands into STRING wrapped to hold in WIDTH columns (default = 79).
+# If PREFIX is given, each line is prefixed with it. If FIRST-PREFIX is
+# specified, then the first line is prefixed with it. As a special case,
+# if the length of FIRST-PREFIX is greater than that of PREFIX, then
+# FIRST-PREFIX will be left alone on the first line.
+#
+# No expansion occurs on the contents STRING, PREFIX, or FIRST-PREFIX,
+# although quadrigraphs are correctly recognized.
+#
+# Typical outputs are:
+#
+# m4_text_wrap([Short string */], [ ], [/* ], 20)
+# => /* Short string */
+#
+# m4_text_wrap([Much longer string */], [ ], [/* ], 20)
+# => /* Much longer
+# => string */
+#
+# m4_text_wrap([Short doc.], [ ], [ --short ], 30)
+# => --short Short doc.
+#
+# m4_text_wrap([Short doc.], [ ], [ --too-wide ], 30)
+# => --too-wide
+# => Short doc.
+#
+# m4_text_wrap([Super long documentation.], [ ], [ --too-wide ], 30)
+# => --too-wide
+# => Super long
+# => documentation.
+#
+# FIXME: there is no checking of a longer PREFIX than WIDTH, but do
+# we really want to bother with people trying each single corner
+# of a software?
+#
+# This macro does not leave a trailing space behind the last word of a line,
+# which complicates it a bit. The algorithm is otherwise stupid and simple:
+# all the words are preceded by m4_Separator which is defined to empty for
+# the first word, and then ` ' (single space) for all the others.
+#
+# The algorithm uses a helper that uses $2 through $4 directly, rather than
+# using local variables, to avoid m4_defn overhead, or expansion swallowing
+# any $. It also bypasses m4_popdef overhead with _m4_popdef since no user
+# macro expansion occurs in the meantime. Also, the definition is written
+# with m4_do, to avoid time wasted on dnl during expansion (since this is
+# already a time-consuming macro).
+m4_define([m4_text_wrap],
+[_$0([$1], [$2], m4_if([$3], [], [[$2]], [[$3]]),
+ m4_if([$4], [], [79], [[$4]]))])
+m4_define([_m4_text_wrap],
+m4_do(dnl set up local variables, to avoid repeated calculations
+[[m4_pushdef([m4_Indent], m4_qlen([$2]))]],
+[[m4_pushdef([m4_Cursor], m4_qlen([$3]))]],
+[[m4_pushdef([m4_Separator], [m4_define([m4_Separator], [ ])])]],
+dnl expand the first prefix, then check its length vs. regular prefix
+dnl same length: nothing special
+dnl prefix1 longer: output on line by itself, and reset cursor
+dnl prefix1 shorter: pad to length of prefix, and reset cursor
+[[[$3]m4_cond([m4_Cursor], m4_Indent, [],
+ [m4_eval(m4_Cursor > m4_Indent)], [1], [
+[$2]m4_define([m4_Cursor], m4_Indent)],
+ [m4_format([%*s], m4_max([0],
+ m4_eval(m4_Indent - m4_Cursor)), [])m4_define([m4_Cursor], m4_Indent)])]],
+dnl now, for each word, compute the curser after the word is output, then
+dnl check if the cursor would exceed the wrap column
+dnl if so, reset cursor, and insert newline and prefix
+dnl if not, insert the separator (usually a space)
+dnl either way, insert the word
+[[m4_foreach_w([m4_Word], [$1],
+ [m4_define([m4_Cursor],
+ m4_eval(m4_Cursor + m4_qlen(_m4_defn([m4_Word]))
+ + 1))m4_if(m4_eval(m4_Cursor > ([$4])),
+ [1], [m4_define([m4_Cursor],
+ m4_eval(m4_Indent + m4_qlen(_m4_defn([m4_Word])) + 1))
+[$2]],
+ [m4_Separator[]])_m4_defn([m4_Word])])]],
+dnl finally, clean up the local variabls
+[[_m4_popdef([m4_Separator], [m4_Cursor], [m4_Indent])]]))
+
+
+# m4_text_box(MESSAGE, [FRAME-CHARACTER = `-'])
+# ---------------------------------------------
+# Turn MESSAGE into:
+# ## ------- ##
+# ## MESSAGE ##
+# ## ------- ##
+# using FRAME-CHARACTER in the border.
+m4_define([m4_text_box],
+[m4_pushdef([m4_Border],
+ m4_translit(m4_format([%*s], m4_qlen(m4_expand([$1])), []),
+ [ ], m4_if([$2], [], [[-]], [[$2]])))dnl
+@%:@@%:@ m4_Border @%:@@%:@
+@%:@@%:@ $1 @%:@@%:@
+@%:@@%:@ m4_Border @%:@@%:@_m4_popdef([m4_Border])dnl
+])
+
+
+# m4_qlen(STRING)
+# ---------------
+# Expands to the length of STRING after autom4te converts all quadrigraphs.
+#
+# Avoid bpatsubsts for the common case of no quadrigraphs.
+m4_define([m4_qlen],
+[m4_if(m4_index([$1], [@]), [-1], [m4_len([$1])],
+ [m4_len(m4_bpatsubst([[$1]],
+ [@\(\(<:\|:>\|S|\|%:\|\{:\|:\}\)\(@\)\|&t@\)],
+ [\3]))])])
+
+
+# m4_qdelta(STRING)
+# -----------------
+# Expands to the net change in the length of STRING from autom4te converting the
+# quadrigraphs in STRING. This number is always negative or zero.
+m4_define([m4_qdelta],
+[m4_eval(m4_qlen([$1]) - m4_len([$1]))])
+
+
+
+## ----------------------- ##
+## 13. Number processing. ##
+## ----------------------- ##
+
+# m4_cmp(A, B)
+# ------------
+# Compare two integer expressions.
+# A < B -> -1
+# A = B -> 0
+# A > B -> 1
+m4_define([m4_cmp],
+[m4_eval((([$1]) > ([$2])) - (([$1]) < ([$2])))])
+
+
+# m4_list_cmp(A, B)
+# -----------------
+#
+# Compare the two lists of integer expressions A and B. For instance:
+# m4_list_cmp([1, 0], [1]) -> 0
+# m4_list_cmp([1, 0], [1, 0]) -> 0
+# m4_list_cmp([1, 2], [1, 0]) -> 1
+# m4_list_cmp([1, 2, 3], [1, 2]) -> 1
+# m4_list_cmp([1, 2, -3], [1, 2]) -> -1
+# m4_list_cmp([1, 0], [1, 2]) -> -1
+# m4_list_cmp([1], [1, 2]) -> -1
+# m4_define([xa], [oops])dnl
+# m4_list_cmp([[0xa]], [5+5]) -> 0
+#
+# Rather than face the overhead of m4_case, we use a helper function whose
+# expansion includes the name of the macro to invoke on the tail, either
+# m4_ignore or m4_unquote. This is particularly useful when comparing
+# long lists, since less text is being expanded for deciding when to end
+# recursion. The recursion is between a pair of macros that alternate
+# which list is trimmed by one element; this is more efficient than
+# calling m4_cdr on both lists from a single macro. Guarantee exactly
+# one expansion of both lists' side effects.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_list_cmp],
+[_$0_raw(m4_dquote($1), m4_dquote($2))])
+
+m4_define([_m4_list_cmp_raw],
+[m4_if([$1], [$2], [0], [_m4_list_cmp_1([$1], $2)])])
+
+m4_define([_m4_list_cmp],
+[m4_if([$1], [], [0m4_ignore], [$2], [0], [m4_unquote], [$2m4_ignore])])
+
+m4_define([_m4_list_cmp_1],
+[_m4_list_cmp_2([$2], [m4_shift2($@)], $1)])
+
+m4_define([_m4_list_cmp_2],
+[_m4_list_cmp([$1$3], m4_cmp([$3+0], [$1+0]))(
+ [_m4_list_cmp_1(m4_dquote(m4_shift3($@)), $2)])])
+
+# m4_max(EXPR, ...)
+# m4_min(EXPR, ...)
+# -----------------
+# Return the decimal value of the maximum (or minimum) in a series of
+# integer expressions.
+#
+# M4 1.4.x doesn't provide ?:. Hence this huge m4_eval. Avoid m4_eval
+# if both arguments are identical, but be aware of m4_max(0xa, 10) (hence
+# the use of <=, not just <, in the second multiply).
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_max],
+[m4_if([$#], [0], [m4_fatal([too few arguments to $0])],
+ [$#], [1], [m4_eval([$1])],
+ [$#$1], [2$2], [m4_eval([$1])],
+ [$#], [2], [_$0($@)],
+ [_m4_minmax([_$0], $@)])])
+
+m4_define([_m4_max],
+[m4_eval((([$1]) > ([$2])) * ([$1]) + (([$1]) <= ([$2])) * ([$2]))])
+
+m4_define([m4_min],
+[m4_if([$#], [0], [m4_fatal([too few arguments to $0])],
+ [$#], [1], [m4_eval([$1])],
+ [$#$1], [2$2], [m4_eval([$1])],
+ [$#], [2], [_$0($@)],
+ [_m4_minmax([_$0], $@)])])
+
+m4_define([_m4_min],
+[m4_eval((([$1]) < ([$2])) * ([$1]) + (([$1]) >= ([$2])) * ([$2]))])
+
+# _m4_minmax(METHOD, ARG1, ARG2...)
+# ---------------------------------
+# Common recursion code for m4_max and m4_min. METHOD must be _m4_max
+# or _m4_min, and there must be at least two arguments to combine.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([_m4_minmax],
+[m4_if([$#], [3], [$1([$2], [$3])],
+ [$0([$1], $1([$2], [$3]), m4_shift3($@))])])
+
+
+# m4_sign(A)
+# ----------
+# The sign of the integer expression A.
+m4_define([m4_sign],
+[m4_eval((([$1]) > 0) - (([$1]) < 0))])
+
+
+
+## ------------------------ ##
+## 14. Version processing. ##
+## ------------------------ ##
+
+
+# m4_version_unletter(VERSION)
+# ----------------------------
+# Normalize beta version numbers with letters to numeric expressions, which
+# can then be handed to m4_eval for the purpose of comparison.
+#
+# Nl -> (N+1).-1.(l#)
+#
+# for example:
+# [2.14a] -> [2.14+1.-1.[0r36:a]] -> 2.15.-1.10
+# [2.14b] -> [2.15+1.-1.[0r36:b]] -> 2.15.-1.11
+# [2.61aa.b] -> [2.61+1.-1.[0r36:aa],+1.-1.[0r36:b]] -> 2.62.-1.370.1.-1.11
+#
+# This macro expects reasonable version numbers, but can handle double
+# letters and does not expand any macros. Original version strings can
+# use both `.' and `-' separators.
+#
+# Inline constant expansions, to avoid m4_defn overhead.
+# _m4_version_unletter is the real workhorse used by m4_version_compare,
+# but since [0r36:a] is less readable than 10, we provide a wrapper for
+# human use.
+m4_define([m4_version_unletter],
+[m4_map_sep([m4_eval], [.],
+ m4_dquote(m4_dquote_elt(m4_unquote(_$0([$1])))))])
+m4_define([_m4_version_unletter],
+[m4_bpatsubst(m4_translit([[[$1]]], [.-], [,,]),]dnl
+m4_dquote(m4_dquote(m4_defn([m4_cr_Letters])))[[+],
+ [+1,-1,[0r36:\&]])])
+
+
+# m4_version_compare(VERSION-1, VERSION-2)
+# ----------------------------------------
+# Compare the two version numbers and expand into
+# -1 if VERSION-1 < VERSION-2
+# 0 if =
+# 1 if >
+#
+# Since _m4_version_unletter does not output side effects, we can
+# safely bypass the overhead of m4_version_cmp.
+m4_define([m4_version_compare],
+[_m4_list_cmp_raw(_m4_version_unletter([$1]), _m4_version_unletter([$2]))])
+
+
+# m4_PACKAGE_NAME
+# m4_PACKAGE_TARNAME
+# m4_PACKAGE_VERSION
+# m4_PACKAGE_STRING
+# m4_PACKAGE_BUGREPORT
+# --------------------
+# If m4sugar/version.m4 is present, then define version strings. This
+# file is optional, provided by Autoconf but absent in Bison.
+m4_sinclude([m4sugar/version.m4])
+
+
+# m4_version_prereq(VERSION, [IF-OK], [IF-NOT = FAIL])
+# ----------------------------------------------------
+# Check this Autoconf version against VERSION.
+m4_define([m4_version_prereq],
+m4_ifdef([m4_PACKAGE_VERSION],
+[[m4_if(m4_version_compare(]m4_dquote(m4_defn([m4_PACKAGE_VERSION]))[, [$1]),
+ [-1],
+ [m4_default([$3],
+ [m4_fatal([Autoconf version $1 or higher is required],
+ [63])])],
+ [$2])]],
+[[m4_fatal([m4sugar/version.m4 not found])]]))
+
+
+## ------------------ ##
+## 15. Set handling. ##
+## ------------------ ##
+
+# Autoconf likes to create arbitrarily large sets; for example, as of
+# this writing, the configure.ac for coreutils tracks a set of more
+# than 400 AC_SUBST. How do we track all of these set members,
+# without introducing duplicates? We could use m4_append_uniq, with
+# the set NAME residing in the contents of the macro NAME.
+# Unfortunately, m4_append_uniq is quadratic for set creation, because
+# it costs O(n) to search the string for each of O(n) insertions; not
+# to mention that with m4 1.4.x, even using m4_append is slow, costing
+# O(n) rather than O(1) per insertion. Other set operations, not used
+# by Autoconf but still possible by manipulation of the definition
+# tracked in macro NAME, include O(n) deletion of one element and O(n)
+# computation of set size. Because the set is exposed to the user via
+# the definition of a single macro, we cannot cache any data about the
+# set without risking the cache being invalidated by the user
+# redefining NAME.
+#
+# Can we do better? Yes, because m4 gives us an O(1) search function
+# for free: ifdef. Additionally, even m4 1.4.x gives us an O(1)
+# insert operation for free: pushdef. But to use these, we must
+# represent the set via a group of macros; to keep the set consistent,
+# we must hide the set so that the user can only manipulate it through
+# accessor macros. The contents of the set are maintained through two
+# access points; _m4_set([name]) is a pushdef stack of values in the
+# set, useful for O(n) traversal of the set contents; while the
+# existence of _m4_set([name],value) with no particular value is
+# useful for O(1) querying of set membership. And since the user
+# cannot externally manipulate the set, we are free to add additional
+# caching macros for other performance improvements. Deletion can be
+# O(1) per element rather than O(n), by reworking the definition of
+# _m4_set([name],value) to be 0 or 1 based on current membership, and
+# adding _m4_set_cleanup(name) to defer the O(n) cleanup of
+# _m4_set([name]) until we have another reason to do an O(n)
+# traversal. The existence of _m4_set_cleanup(name) can then be used
+# elsewhere to determine if we must dereference _m4_set([name],value),
+# or assume that definition implies set membership. Finally, size can
+# be tracked in an O(1) fashion with _m4_set_size(name).
+#
+# The quoting in _m4_set([name],value) is chosen so that there is no
+# ambiguity with a set whose name contains a comma, and so that we can
+# supply the value via _m4_defn([_m4_set([name])]) without needing any
+# quote manipulation.
+
+# m4_set_add(SET, VALUE, [IF-UNIQ], [IF-DUP])
+# -------------------------------------------
+# Add VALUE as an element of SET. Expand IF-UNIQ on the first
+# addition, and IF-DUP if it is already in the set. Addition of one
+# element is O(1), such that overall set creation is O(n).
+#
+# We do not want to add a duplicate for a previously deleted but
+# unpruned element, but it is just as easy to check existence directly
+# as it is to query _m4_set_cleanup($1).
+m4_define([m4_set_add],
+[m4_ifdef([_m4_set([$1],$2)],
+ [m4_if(m4_indir([_m4_set([$1],$2)]), [0],
+ [m4_define([_m4_set([$1],$2)],
+ [1])_m4_set_size([$1], [m4_incr])$3], [$4])],
+ [m4_define([_m4_set([$1],$2)],
+ [1])m4_pushdef([_m4_set([$1])],
+ [$2])_m4_set_size([$1], [m4_incr])$3])])
+
+# m4_set_add_all(SET, VALUE...)
+# -----------------------------
+# Add each VALUE into SET. This is O(n) in the number of VALUEs, and
+# can be faster than calling m4_set_add for each VALUE.
+#
+# Implement two recursion helpers; the check variant is slower but
+# handles the case where an element has previously been removed but
+# not pruned. The recursion helpers ignore their second argument, so
+# that we can use the faster m4_shift2 and 2 arguments, rather than
+# _m4_shift2 and one argument, as the signal to end recursion.
+#
+# Please keep foreach.m4 in sync with any adjustments made here.
+m4_define([m4_set_add_all],
+[m4_define([_m4_set_size($1)], m4_eval(m4_set_size([$1])
+ + m4_len(m4_ifdef([_m4_set_cleanup($1)], [_$0_check], [_$0])([$1], $@))))])
+
+m4_define([_m4_set_add_all],
+[m4_if([$#], [2], [],
+ [m4_ifdef([_m4_set([$1],$3)], [],
+ [m4_define([_m4_set([$1],$3)], [1])m4_pushdef([_m4_set([$1])],
+ [$3])-])$0([$1], m4_shift2($@))])])
+
+m4_define([_m4_set_add_all_check],
+[m4_if([$#], [2], [],
+ [m4_set_add([$1], [$3])$0([$1], m4_shift2($@))])])
+
+# m4_set_contains(SET, VALUE, [IF-PRESENT], [IF-ABSENT])
+# ------------------------------------------------------
+# Expand IF-PRESENT if SET contains VALUE, otherwise expand IF-ABSENT.
+# This is always O(1).
+m4_define([m4_set_contains],
+[m4_ifdef([_m4_set_cleanup($1)],
+ [m4_if(m4_ifdef([_m4_set([$1],$2)],
+ [m4_indir([_m4_set([$1],$2)])], [0]), [1], [$3], [$4])],
+ [m4_ifdef([_m4_set([$1],$2)], [$3], [$4])])])
+
+# m4_set_contents(SET, [SEP])
+# ---------------------------
+# Expand to a single string containing all the elements in SET,
+# separated by SEP, without modifying SET. No provision is made for
+# disambiguating set elements that contain non-empty SEP as a
+# sub-string, or for recognizing a set that contains only the empty
+# string. Order of the output is not guaranteed. If any elements
+# have been previously removed from the set, this action will prune
+# the unused memory. This is O(n) in the size of the set before
+# pruning.
+#
+# Use _m4_popdef for speed. The existence of _m4_set_cleanup($1)
+# determines which version of _1 helper we use.
+m4_define([m4_set_contents],
+[m4_ifdef([_m4_set_cleanup($1)], [_$0_1c], [_$0_1])([$1])_$0_2([$1],
+ [_m4_defn([_m4_set_($1)])], [[$2]])])
+
+# _m4_set_contents_1(SET)
+# _m4_set_contents_1c(SET)
+# _m4_set_contents_2(SET, SEP, PREP)
+# ----------------------------------
+# Expand to a list of quoted elements currently in the set, separated
+# by SEP, and moving PREP in front of SEP on recursion. To avoid
+# nesting limit restrictions, the algorithm must be broken into two
+# parts; _1 destructively copies the stack in reverse into
+# _m4_set_($1), producing no output; then _2 destructively copies
+# _m4_set_($1) back into the stack in reverse. SEP is expanded while
+# _m4_set_($1) contains the current element, so a SEP containing
+# _m4_defn([_m4_set_($1)]) can produce output in the order the set was
+# created. Behavior is undefined if SEP tries to recursively list or
+# modify SET in any way other than calling m4_set_remove on the
+# current element. Use _1 if all entries in the stack are guaranteed
+# to be in the set, and _1c to prune removed entries. Uses _m4_defn
+# and _m4_popdef for speed.
+m4_define([_m4_set_contents_1],
+[m4_ifdef([_m4_set([$1])], [m4_pushdef([_m4_set_($1)],
+ _m4_defn([_m4_set([$1])]))_m4_popdef([_m4_set([$1])])$0([$1])])])
+
+m4_define([_m4_set_contents_1c],
+[m4_ifdef([_m4_set([$1])],
+ [m4_set_contains([$1], _m4_defn([_m4_set([$1])]),
+ [m4_pushdef([_m4_set_($1)], _m4_defn([_m4_set([$1])]))],
+ [_m4_popdef([_m4_set([$1],]_m4_defn(
+ [_m4_set([$1])])[)])])_m4_popdef([_m4_set([$1])])$0([$1])],
+ [_m4_popdef([_m4_set_cleanup($1)])])])
+
+m4_define([_m4_set_contents_2],
+[m4_ifdef([_m4_set_($1)], [m4_pushdef([_m4_set([$1])],
+ _m4_defn([_m4_set_($1)]))$2[]_m4_popdef([_m4_set_($1)])$0([$1], [$3$2])])])
+
+# m4_set_delete(SET)
+# ------------------
+# Delete all elements in SET, and reclaim any memory occupied by the
+# set. This is O(n) in the set size.
+#
+# Use _m4_defn and _m4_popdef for speed.
+m4_define([m4_set_delete],
+[m4_ifdef([_m4_set([$1])],
+ [_m4_popdef([_m4_set([$1],]_m4_defn([_m4_set([$1])])[)],
+ [_m4_set([$1])])$0([$1])],
+ [m4_ifdef([_m4_set_cleanup($1)],
+ [_m4_popdef([_m4_set_cleanup($1)])])m4_ifdef(
+ [_m4_set_size($1)],
+ [_m4_popdef([_m4_set_size($1)])])])])
+
+# m4_set_difference(SET1, SET2)
+# -----------------------------
+# Produce a LIST of quoted elements that occur in SET1 but not SET2.
+# Output a comma prior to any elements, to distinguish the empty
+# string from no elements. This can be directly used as a series of
+# arguments, such as for m4_join, or wrapped inside quotes for use in
+# m4_foreach. Order of the output is not guaranteed.
+#
+# Short-circuit the idempotence relation. Use _m4_defn for speed.
+m4_define([m4_set_difference],
+[m4_if([$1], [$2], [],
+ [m4_set_foreach([$1], [_m4_element],
+ [m4_set_contains([$2], _m4_defn([_m4_element]), [],
+ [,_m4_defn([_m4_element])])])])])
+
+# m4_set_dump(SET, [SEP])
+# -----------------------
+# Expand to a single string containing all the elements in SET,
+# separated by SEP, then delete SET. In general, if you only need to
+# list the contents once, this is faster than m4_set_contents. No
+# provision is made for disambiguating set elements that contain
+# non-empty SEP as a sub-string. Order of the output is not
+# guaranteed. This is O(n) in the size of the set before pruning.
+#
+# Use _m4_popdef for speed. Use existence of _m4_set_cleanup($1) to
+# decide if more expensive recursion is needed.
+m4_define([m4_set_dump],
+[m4_ifdef([_m4_set_size($1)],
+ [_m4_popdef([_m4_set_size($1)])])m4_ifdef([_m4_set_cleanup($1)],
+ [_$0_check], [_$0])([$1], [], [$2])])
+
+# _m4_set_dump(SET, SEP, PREP)
+# _m4_set_dump_check(SET, SEP, PREP)
+# ----------------------------------
+# Print SEP and the current element, then delete the element and
+# recurse with empty SEP changed to PREP. The check variant checks
+# whether the element has been previously removed. Use _m4_defn and
+# _m4_popdef for speed.
+m4_define([_m4_set_dump],
+[m4_ifdef([_m4_set([$1])],
+ [[$2]_m4_defn([_m4_set([$1])])_m4_popdef([_m4_set([$1],]_m4_defn(
+ [_m4_set([$1])])[)], [_m4_set([$1])])$0([$1], [$2$3])])])
+
+m4_define([_m4_set_dump_check],
+[m4_ifdef([_m4_set([$1])],
+ [m4_set_contains([$1], _m4_defn([_m4_set([$1])]),
+ [[$2]_m4_defn([_m4_set([$1])])])_m4_popdef(
+ [_m4_set([$1],]_m4_defn([_m4_set([$1])])[)],
+ [_m4_set([$1])])$0([$1], [$2$3])],
+ [_m4_popdef([_m4_set_cleanup($1)])])])
+
+# m4_set_empty(SET, [IF-EMPTY], [IF-ELEMENTS])
+# --------------------------------------------
+# Expand IF-EMPTY if SET has no elements, otherwise IF-ELEMENTS.
+m4_define([m4_set_empty],
+[m4_ifdef([_m4_set_size($1)],
+ [m4_if(m4_indir([_m4_set_size($1)]), [0], [$2], [$3])], [$2])])
+
+# m4_set_foreach(SET, VAR, ACTION)
+# --------------------------------
+# For each element of SET, define VAR to the element and expand
+# ACTION. ACTION should not recursively list SET's contents, add
+# elements to SET, nor delete any element from SET except the one
+# currently in VAR. The order that the elements are visited in is not
+# guaranteed. This is faster than the corresponding m4_foreach([VAR],
+# m4_indir([m4_dquote]m4_set_listc([SET])), [ACTION])
+m4_define([m4_set_foreach],
+[m4_pushdef([$2])m4_ifdef([_m4_set_cleanup($1)],
+ [_m4_set_contents_1c], [_m4_set_contents_1])([$1])_m4_set_contents_2([$1],
+ [m4_define([$2], _m4_defn([_m4_set_($1)]))$3[]])m4_popdef([$2])])
+
+# m4_set_intersection(SET1, SET2)
+# -------------------------------
+# Produce a LIST of quoted elements that occur in both SET1 or SET2.
+# Output a comma prior to any elements, to distinguish the empty
+# string from no elements. This can be directly used as a series of
+# arguments, such as for m4_join, or wrapped inside quotes for use in
+# m4_foreach. Order of the output is not guaranteed.
+#
+# Iterate over the smaller set, and short-circuit the idempotence
+# relation. Use _m4_defn for speed.
+m4_define([m4_set_intersection],
+[m4_if([$1], [$2], [m4_set_listc([$1])],
+ m4_eval(m4_set_size([$2]) < m4_set_size([$1])), [1], [$0([$2], [$1])],
+ [m4_set_foreach([$1], [_m4_element],
+ [m4_set_contains([$2], _m4_defn([_m4_element]),
+ [,_m4_defn([_m4_element])])])])])
+
+# m4_set_list(SET)
+# m4_set_listc(SET)
+# -----------------
+# Produce a LIST of quoted elements of SET. This can be directly used
+# as a series of arguments, such as for m4_join or m4_set_add_all, or
+# wrapped inside quotes for use in m4_foreach or m4_map. With
+# m4_set_list, there is no way to distinguish an empty set from a set
+# containing only the empty string; with m4_set_listc, a leading comma
+# is output if there are any elements.
+m4_define([m4_set_list],
+[m4_ifdef([_m4_set_cleanup($1)], [_m4_set_contents_1c],
+ [_m4_set_contents_1])([$1])_m4_set_contents_2([$1],
+ [_m4_defn([_m4_set_($1)])], [,])])
+
+m4_define([m4_set_listc],
+[m4_ifdef([_m4_set_cleanup($1)], [_m4_set_contents_1c],
+ [_m4_set_contents_1])([$1])_m4_set_contents_2([$1],
+ [,_m4_defn([_m4_set_($1)])])])
+
+# m4_set_remove(SET, VALUE, [IF-PRESENT], [IF-ABSENT])
+# ----------------------------------------------------
+# If VALUE is an element of SET, delete it and expand IF-PRESENT.
+# Otherwise expand IF-ABSENT. Deleting a single value is O(1),
+# although it leaves memory occupied until the next O(n) traversal of
+# the set which will compact the set.
+#
+# Optimize if the element being removed is the most recently added,
+# since defining _m4_set_cleanup($1) slows down so many other macros.
+# In particular, this plays well with m4_set_foreach.
+m4_define([m4_set_remove],
+[m4_set_contains([$1], [$2], [_m4_set_size([$1],
+ [m4_decr])m4_if(_m4_defn([_m4_set([$1])]), [$2],
+ [_m4_popdef([_m4_set([$1],$2)], [_m4_set([$1])])],
+ [m4_define([_m4_set_cleanup($1)])m4_define(
+ [_m4_set([$1],$2)], [0])])$3], [$4])])
+
+# m4_set_size(SET)
+# ----------------
+# Expand to the number of elements currently in SET. This operation
+# is O(1), and thus more efficient than m4_count(m4_set_list([SET])).
+m4_define([m4_set_size],
+[m4_ifdef([_m4_set_size($1)], [m4_indir([_m4_set_size($1)])], [0])])
+
+# _m4_set_size(SET, ACTION)
+# -------------------------
+# ACTION must be either m4_incr or m4_decr, and the size of SET is
+# changed accordingly. If the set is empty, ACTION must not be
+# m4_decr.
+m4_define([_m4_set_size],
+[m4_define([_m4_set_size($1)],
+ m4_ifdef([_m4_set_size($1)], [$2(m4_indir([_m4_set_size($1)]))],
+ [1]))])
+
+# m4_set_union(SET1, SET2)
+# ------------------------
+# Produce a LIST of double quoted elements that occur in either SET1
+# or SET2, without duplicates. Output a comma prior to any elements,
+# to distinguish the empty string from no elements. This can be
+# directly used as a series of arguments, such as for m4_join, or
+# wrapped inside quotes for use in m4_foreach. Order of the output is
+# not guaranteed.
+#
+# We can rely on the fact that m4_set_listc prunes SET1, so we don't
+# need to check _m4_set([$1],element) for 0. Use _m4_defn for speed.
+# Short-circuit the idempotence relation.
+m4_define([m4_set_union],
+[m4_set_listc([$1])m4_if([$1], [$2], [], [m4_set_foreach([$2], [_m4_element],
+ [m4_ifdef([_m4_set([$1],]_m4_defn([_m4_element])[)], [],
+ [,_m4_defn([_m4_element])])])])])
+
+
+## ------------------- ##
+## 16. File handling. ##
+## ------------------- ##
+
+
+# It is a real pity that M4 comes with no macros to bind a diversion
+# to a file. So we have to deal without, which makes us a lot more
+# fragile than we should.
+
+
+# m4_file_append(FILE-NAME, CONTENT)
+# ----------------------------------
+m4_define([m4_file_append],
+[m4_syscmd([cat >>$1 <<_m4eof
+$2
+_m4eof
+])
+m4_if(m4_sysval, [0], [],
+ [m4_fatal([$0: cannot write: $1])])])
+
+
+
+## ------------------------ ##
+## 17. Setting M4sugar up. ##
+## ------------------------ ##
+
+
+# m4_init
+# -------
+# Initialize the m4sugar language.
+m4_define([m4_init],
+[# All the M4sugar macros start with `m4_', except `dnl' kept as is
+# for sake of simplicity.
+m4_pattern_forbid([^_?m4_])
+m4_pattern_forbid([^dnl$])
+
+# If __m4_version__ is defined, we assume that we are being run by M4
+# 1.6 or newer, and thus that $@ recursion is linear and debugmode(d)
+# is available for faster checks of dereferencing undefined macros.
+# But if it is missing, we assume we are being run by M4 1.4.x, that
+# $@ recursion is quadratic, and that we need foreach-based
+# replacement macros. Use the raw builtin to avoid tripping up
+# include tracing.
+m4_ifdef([__m4_version__],
+[m4_debugmode([+d])
+m4_copy([_m4_defn], [m4_defn])
+m4_copy([_m4_popdef], [m4_popdef])
+m4_copy([_m4_undefine], [m4_undefine])],
+[m4_builtin([include], [m4sugar/foreach.m4])])
+
+# _m4_divert_diversion should be defined:
+m4_divert_push([KILL])
+
+# Check the divert push/pop perfect balance.
+m4_wrap([m4_divert_pop([])
+ m4_ifdef([_m4_divert_diversion],
+ [m4_fatal([$0: unbalanced m4_divert_push:]_m4_divert_n_stack)])[]])
+])
diff --git a/tools/mhmake/src/bisondata/yacc.c b/tools/mhmake/src/bisondata/yacc.c
new file mode 100644
index 000000000..19f77a5fb
--- /dev/null
+++ b/tools/mhmake/src/bisondata/yacc.c
@@ -0,0 +1,1741 @@
+ -*- C -*-
+
+# Yacc compatible skeleton for Bison
+
+# Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
+# 2007, 2008 Free Software Foundation, Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Check the value of %define api.push_pull.
+b4_percent_define_default([[api.push_pull]], [[pull]])
+b4_percent_define_check_values([[[[api.push_pull]],
+ [[pull]], [[push]], [[both]]]])
+b4_define_flag_if([pull]) m4_define([b4_pull_flag], [[1]])
+b4_define_flag_if([push]) m4_define([b4_push_flag], [[1]])
+m4_case(b4_percent_define_get([[api.push_pull]]),
+ [pull], [m4_define([b4_push_flag], [[0]])],
+ [push], [m4_define([b4_pull_flag], [[0]])])
+
+# Handle BISON_USE_PUSH_FOR_PULL for the test suite. So that push parsing
+# tests function as written, don't let BISON_USE_PUSH_FOR_PULL modify Bison's
+# behavior at all when push parsing is already requested.
+b4_define_flag_if([use_push_for_pull])
+b4_use_push_for_pull_if([
+ b4_push_if([m4_define([b4_use_push_for_pull_flag], [[0]])],
+ [m4_define([b4_push_flag], [[1]])])])
+
+m4_include(b4_pkgdatadir/[c.m4])
+
+## ---------------- ##
+## Default values. ##
+## ---------------- ##
+
+# Stack parameters.
+m4_define_default([b4_stack_depth_max], [10000])
+m4_define_default([b4_stack_depth_init], [200])
+
+
+## ------------------------ ##
+## Pure/impure interfaces. ##
+## ------------------------ ##
+
+b4_percent_define_default([[api.pure]], [[false]])
+b4_define_flag_if([pure])
+m4_define([b4_pure_flag],
+ [b4_percent_define_flag_if([[api.pure]], [[1]], [[0]])])
+
+# b4_yacc_pure_if(IF-TRUE, IF-FALSE)
+# ----------------------------------
+# Expand IF-TRUE, if %pure-parser and %parse-param, IF-FALSE otherwise.
+m4_define([b4_yacc_pure_if],
+[b4_pure_if([m4_ifset([b4_parse_param],
+ [$1], [$2])],
+ [$2])])
+
+
+# b4_yyerror_args
+# ---------------
+# Arguments passed to yyerror: user args plus yylloc.
+m4_define([b4_yyerror_args],
+[b4_yacc_pure_if([b4_locations_if([&yylloc, ])])dnl
+m4_ifset([b4_parse_param], [b4_c_args(b4_parse_param), ])])
+
+
+# b4_lex_param
+# ------------
+# Accumulate in b4_lex_param all the yylex arguments.
+# b4_lex_param arrives quoted twice, but we want to keep only one level.
+m4_define([b4_lex_param],
+m4_dquote(b4_pure_if([[[[YYSTYPE *]], [[&yylval]]][]dnl
+b4_locations_if([, [[YYLTYPE *], [&yylloc]]])m4_ifdef([b4_lex_param], [, ])])dnl
+m4_ifdef([b4_lex_param], b4_lex_param)))
+
+
+## ------------ ##
+## Data Types. ##
+## ------------ ##
+
+# b4_int_type(MIN, MAX)
+# ---------------------
+# Return the smallest int type able to handle numbers ranging from
+# MIN to MAX (included). Overwrite the version from c.m4, which
+# uses only C89 types, so that the user can override the shorter
+# types, and so that pre-C89 compilers are handled correctly.
+m4_define([b4_int_type],
+[m4_if(b4_ints_in($@, [0], [255]), [1], [yytype_uint8],
+ b4_ints_in($@, [-128], [127]), [1], [yytype_int8],
+
+ b4_ints_in($@, [0], [65535]), [1], [yytype_uint16],
+ b4_ints_in($@, [-32768], [32767]), [1], [yytype_int16],
+
+ m4_eval([0 <= $1]), [1], [unsigned int],
+
+ [int])])
+
+
+## ----------------- ##
+## Semantic Values. ##
+## ----------------- ##
+
+
+# b4_lhs_value([TYPE])
+# --------------------
+# Expansion of $<TYPE>$.
+m4_define([b4_lhs_value],
+[(yyval[]m4_ifval([$1], [.$1]))])
+
+
+# b4_rhs_value(RULE-LENGTH, NUM, [TYPE])
+# --------------------------------------
+# Expansion of $<TYPE>NUM, where the current rule has RULE-LENGTH
+# symbols on RHS.
+m4_define([b4_rhs_value],
+[(yyvsp@{($2) - ($1)@}m4_ifval([$3], [.$3]))])
+
+
+
+## ----------- ##
+## Locations. ##
+## ----------- ##
+
+# b4_lhs_location()
+# -----------------
+# Expansion of @$.
+m4_define([b4_lhs_location],
+[(yyloc)])
+
+
+# b4_rhs_location(RULE-LENGTH, NUM)
+# ---------------------------------
+# Expansion of @NUM, where the current rule has RULE-LENGTH symbols
+# on RHS.
+m4_define([b4_rhs_location],
+[(yylsp@{($2) - ($1)@})])
+
+
+
+## --------------------------------------------------------- ##
+## Defining symbol actions, e.g., printers and destructors. ##
+## --------------------------------------------------------- ##
+
+# We do want M4 expansion after # for CPP macros.
+m4_changecom()
+m4_divert_push(0)dnl
+@output(b4_parser_file_name@)
+b4_copyright([Skeleton implementation for Bison's Yacc-like parsers in C],dnl '
+ [1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006])[
+
+/* C LALR(1) parser skeleton written by Richard Stallman, by
+ simplifying the original so-called "semantic" parser. */
+
+/* All symbols defined below should begin with yy or YY, to avoid
+ infringing on user name space. This should be done even for local
+ variables, as they might otherwise be expanded by user macros.
+ There are some unavoidable exceptions within include files to
+ define necessary library symbols; they are noted "INFRINGES ON
+ USER NAME SPACE" below. */
+
+]b4_identification
+b4_percent_code_get([[top]])[]dnl
+m4_if(b4_prefix, [yy], [],
+[[/* Substitute the variable and function names. */
+]b4_pull_if([[#define yyparse ]b4_prefix[parse
+]])b4_push_if([[#define yypush_parse ]b4_prefix[push_parse
+]b4_pull_if([[#define yypull_parse ]b4_prefix[pull_parse
+]])[#define yypstate_new ]b4_prefix[pstate_new
+#define yypstate_delete ]b4_prefix[pstate_delete
+#define yypstate ]b4_prefix[pstate
+]])[#define yylex ]b4_prefix[lex
+#define yyerror ]b4_prefix[error
+#define yylval ]b4_prefix[lval
+#define yychar ]b4_prefix[char
+#define yydebug ]b4_prefix[debug
+#define yynerrs ]b4_prefix[nerrs
+]b4_locations_if([[#define yylloc ]b4_prefix[lloc]])])[
+
+/* Copy the first part of user declarations. */
+]b4_user_pre_prologue[
+
+/* Enabling traces. */
+#ifndef YYDEBUG
+# define YYDEBUG ]b4_debug_flag[
+#endif
+
+/* Enabling verbose error messages. */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE ]b4_error_verbose_flag[
+#endif
+
+/* Enabling the token table. */
+#ifndef YYTOKEN_TABLE
+# define YYTOKEN_TABLE ]b4_token_table[
+#endif
+
+]b4_percent_code_get([[requires]])[]dnl
+
+b4_token_enums_defines(b4_tokens)[
+
+#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
+]m4_ifdef([b4_stype],
+[[typedef union ]b4_union_name[
+{
+]b4_user_stype[
+} YYSTYPE;
+# define YYSTYPE_IS_TRIVIAL 1]],
+[m4_if(b4_tag_seen_flag, 0,
+[[typedef int YYSTYPE;
+# define YYSTYPE_IS_TRIVIAL 1]])])[
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+#endif]b4_locations_if([[
+
+#if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED
+typedef struct YYLTYPE
+{
+ int first_line;
+ int first_column;
+ int last_line;
+ int last_column;
+} YYLTYPE;
+# define yyltype YYLTYPE /* obsolescent; will be withdrawn */
+# define YYLTYPE_IS_DECLARED 1
+# define YYLTYPE_IS_TRIVIAL 1
+#endif]])b4_push_if([[
+
+#ifndef YYPUSH_DECLS
+# define YYPUSH_DECLS
+struct yypstate;
+typedef struct yypstate yypstate;
+enum { YYPUSH_MORE = 4 };
+
+]b4_pull_if([b4_c_function_decl([[yyparse]], [[int]], b4_parse_param)
+])b4_c_function_decl([[yypush_parse]], [[int]],
+ [[[yypstate *yyps]], [[yyps]]]b4_pure_if([,
+ [[[int yypushed_char]], [[yypushed_char]]],
+ [[[YYSTYPE const *yypushed_val]], [[yypushed_val]]]b4_locations_if([,
+ [[[YYLTYPE const *yypushed_loc]], [[yypushed_loc]]]])])m4_ifset([b4_parse_param], [,
+ b4_parse_param]))
+b4_pull_if([b4_c_function_decl([[yypull_parse]], [[int]],
+ [[[yypstate *yyps]], [[yyps]]]m4_ifset([b4_parse_param], [,
+ b4_parse_param]))])
+b4_c_function_decl([[yypstate_new]], [[yypstate *]], [[[void]], []])
+b4_c_function_decl([[yypstate_delete]], [[void]],
+ [[[yypstate *yyps]], [[yyps]]])[
+#endif]])
+
+b4_percent_code_get([[provides]])[]dnl
+
+[/* Copy the second part of user declarations. */
+]b4_user_post_prologue
+b4_percent_code_get[]dnl
+
+[#ifdef short
+# undef short
+#endif
+
+#ifdef YYTYPE_UINT8
+typedef YYTYPE_UINT8 yytype_uint8;
+#else
+typedef unsigned char yytype_uint8;
+#endif
+
+#ifdef YYTYPE_INT8
+typedef YYTYPE_INT8 yytype_int8;
+#elif ]b4_c_modern[
+typedef signed char yytype_int8;
+#else
+typedef short int yytype_int8;
+#endif
+
+#ifdef YYTYPE_UINT16
+typedef YYTYPE_UINT16 yytype_uint16;
+#else
+typedef unsigned short int yytype_uint16;
+#endif
+
+#ifdef YYTYPE_INT16
+typedef YYTYPE_INT16 yytype_int16;
+#else
+typedef short int yytype_int16;
+#endif
+
+#ifndef YYSIZE_T
+# ifdef __SIZE_TYPE__
+# define YYSIZE_T __SIZE_TYPE__
+# elif defined size_t
+# define YYSIZE_T size_t
+# elif ! defined YYSIZE_T && ]b4_c_modern[
+# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
+# define YYSIZE_T size_t
+# else
+# define YYSIZE_T unsigned int
+# endif
+#endif
+
+#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
+
+#ifndef YY_
+# if YYENABLE_NLS
+# if ENABLE_NLS
+# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
+# define YY_(msgid) dgettext ("bison-runtime", msgid)
+# endif
+# endif
+# ifndef YY_
+# define YY_(msgid) msgid
+# endif
+#endif
+
+/* Suppress unused-variable warnings by "using" E. */
+#if ! defined lint || defined __GNUC__
+# define YYUSE(e) ((void) (e))
+#else
+# define YYUSE(e) /* empty */
+#endif
+
+/* Identity function, used to suppress warnings about constant conditions. */
+#ifndef lint
+# define YYID(n) (n)
+#else
+]b4_c_function_def([YYID], [static int], [[int yyi], [yyi]])[
+{
+ return yyi;
+}
+#endif
+
+#if ! defined yyoverflow || YYERROR_VERBOSE
+
+]b4_push_if([],
+[[/* The parser invokes alloca or malloc; define the necessary symbols. */
+
+# ifdef YYSTACK_USE_ALLOCA
+# if YYSTACK_USE_ALLOCA
+# ifdef __GNUC__
+# define YYSTACK_ALLOC __builtin_alloca
+# elif defined __BUILTIN_VA_ARG_INCR
+# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
+# elif defined _AIX
+# define YYSTACK_ALLOC __alloca
+# elif defined _MSC_VER
+# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
+# define alloca _alloca
+# else
+# define YYSTACK_ALLOC alloca
+# if ! defined _ALLOCA_H && ! defined _STDLIB_H && ]b4_c_modern[
+# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+# ifndef _STDLIB_H
+# define _STDLIB_H 1
+# endif
+# endif
+# endif
+# endif
+# endif
+
+]])dnl
+[# ifdef YYSTACK_ALLOC
+ /* Pacify GCC's `empty if-body' warning. */
+# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
+# ifndef YYSTACK_ALLOC_MAXIMUM
+ /* The OS might guarantee only one guard page at the bottom of the stack,
+ and a page size can be as small as 4096 bytes. So we cannot safely
+ invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
+ to allow for a few compiler-allocated temporary stack slots. */
+# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
+# endif
+# else
+# define YYSTACK_ALLOC YYMALLOC
+# define YYSTACK_FREE YYFREE
+# ifndef YYSTACK_ALLOC_MAXIMUM
+# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
+# endif
+# if (defined __cplusplus && ! defined _STDLIB_H \
+ && ! ((defined YYMALLOC || defined malloc) \
+ && (defined YYFREE || defined free)))
+# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+# ifndef _STDLIB_H
+# define _STDLIB_H 1
+# endif
+# endif
+# ifndef YYMALLOC
+# define YYMALLOC malloc
+# if ! defined malloc && ! defined _STDLIB_H && ]b4_c_modern[
+void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
+# endif
+# endif
+# ifndef YYFREE
+# define YYFREE free
+# if ! defined free && ! defined _STDLIB_H && ]b4_c_modern[
+void free (void *); /* INFRINGES ON USER NAME SPACE */
+# endif
+# endif
+# endif
+#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
+
+
+#if (! defined yyoverflow \
+ && (! defined __cplusplus \
+ || (]b4_locations_if([[defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \
+ && ]])[defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
+
+/* A type that is properly aligned for any stack member. */
+union yyalloc
+{
+ yytype_int16 yyss_alloc;
+ YYSTYPE yyvs_alloc;]b4_locations_if([
+ YYLTYPE yyls_alloc;])[
+};
+
+/* The size of the maximum gap between one aligned stack and the next. */
+# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
+
+/* The size of an array large to enough to hold all stacks, each with
+ N elements. */
+]b4_locations_if(
+[# define YYSTACK_BYTES(N) \
+ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \
+ + 2 * YYSTACK_GAP_MAXIMUM)],
+[# define YYSTACK_BYTES(N) \
+ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ + YYSTACK_GAP_MAXIMUM)])[
+
+/* Copy COUNT objects from FROM to TO. The source and destination do
+ not overlap. */
+# ifndef YYCOPY
+# if defined __GNUC__ && 1 < __GNUC__
+# define YYCOPY(To, From, Count) \
+ __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
+# else
+# define YYCOPY(To, From, Count) \
+ do \
+ { \
+ YYSIZE_T yyi; \
+ for (yyi = 0; yyi < (Count); yyi++) \
+ (To)[yyi] = (From)[yyi]; \
+ } \
+ while (YYID (0))
+# endif
+# endif
+
+/* Relocate STACK from its old location to the new one. The
+ local variables YYSIZE and YYSTACKSIZE give the old and new number of
+ elements in the stack, and YYPTR gives the new location of the
+ stack. Advance YYPTR to a properly aligned location for the next
+ stack. */
+# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
+ do \
+ { \
+ YYSIZE_T yynewbytes; \
+ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
+ Stack = &yyptr->Stack_alloc; \
+ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+ yyptr += yynewbytes / sizeof (*yyptr); \
+ } \
+ while (YYID (0))
+
+#endif
+
+/* YYFINAL -- State number of the termination state. */
+#define YYFINAL ]b4_final_state_number[
+/* YYLAST -- Last index in YYTABLE. */
+#define YYLAST ]b4_last[
+
+/* YYNTOKENS -- Number of terminals. */
+#define YYNTOKENS ]b4_tokens_number[
+/* YYNNTS -- Number of nonterminals. */
+#define YYNNTS ]b4_nterms_number[
+/* YYNRULES -- Number of rules. */
+#define YYNRULES ]b4_rules_number[
+/* YYNRULES -- Number of states. */
+#define YYNSTATES ]b4_states_number[
+
+/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
+#define YYUNDEFTOK ]b4_undef_token_number[
+#define YYMAXUTOK ]b4_user_token_number_max[
+
+#define YYTRANSLATE(YYX) \
+ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
+
+/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
+static const ]b4_int_type_for([b4_translate])[ yytranslate[] =
+{
+ ]b4_translate[
+};
+
+#if YYDEBUG
+/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
+ YYRHS. */
+static const ]b4_int_type_for([b4_prhs])[ yyprhs[] =
+{
+ ]b4_prhs[
+};
+
+/* YYRHS -- A `-1'-separated list of the rules' RHS. */
+static const ]b4_int_type_for([b4_rhs])[ yyrhs[] =
+{
+ ]b4_rhs[
+};
+
+/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
+static const ]b4_int_type_for([b4_rline])[ yyrline[] =
+{
+ ]b4_rline[
+};
+#endif
+
+#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
+ First, the terminals, then, starting at YYNTOKENS, nonterminals. */
+static const char *const yytname[] =
+{
+ ]b4_tname[
+};
+#endif
+
+# ifdef YYPRINT
+/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
+ token YYLEX-NUM. */
+static const ]b4_int_type_for([b4_toknum])[ yytoknum[] =
+{
+ ]b4_toknum[
+};
+# endif
+
+/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
+static const ]b4_int_type_for([b4_r1])[ yyr1[] =
+{
+ ]b4_r1[
+};
+
+/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
+static const ]b4_int_type_for([b4_r2])[ yyr2[] =
+{
+ ]b4_r2[
+};
+
+/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
+ STATE-NUM when YYTABLE doesn't specify something else to do. Zero
+ means the default is an error. */
+static const ]b4_int_type_for([b4_defact])[ yydefact[] =
+{
+ ]b4_defact[
+};
+
+/* YYDEFGOTO[NTERM-NUM]. */
+static const ]b4_int_type_for([b4_defgoto])[ yydefgoto[] =
+{
+ ]b4_defgoto[
+};
+
+/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+ STATE-NUM. */
+#define YYPACT_NINF ]b4_pact_ninf[
+static const ]b4_int_type_for([b4_pact])[ yypact[] =
+{
+ ]b4_pact[
+};
+
+/* YYPGOTO[NTERM-NUM]. */
+static const ]b4_int_type_for([b4_pgoto])[ yypgoto[] =
+{
+ ]b4_pgoto[
+};
+
+/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
+ positive, shift that token. If negative, reduce the rule which
+ number is the opposite. If zero, do what YYDEFACT says.
+ If YYTABLE_NINF, syntax error. */
+#define YYTABLE_NINF ]b4_table_ninf[
+static const ]b4_int_type_for([b4_table])[ yytable[] =
+{
+ ]b4_table[
+};
+
+static const ]b4_int_type_for([b4_check])[ yycheck[] =
+{
+ ]b4_check[
+};
+
+/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+ symbol of state STATE-NUM. */
+static const ]b4_int_type_for([b4_stos])[ yystos[] =
+{
+ ]b4_stos[
+};
+
+#define yyerrok (yyerrstatus = 0)
+#define yyclearin (yychar = YYEMPTY)
+#define YYEMPTY (-2)
+#define YYEOF 0
+
+#define YYACCEPT goto yyacceptlab
+#define YYABORT goto yyabortlab
+#define YYERROR goto yyerrorlab
+
+
+/* Like YYERROR except do call yyerror. This remains here temporarily
+ to ease the transition to the new meaning of YYERROR, for GCC.
+ Once GCC version 2 has supplanted version 1, this can go. */
+
+#define YYFAIL goto yyerrlab
+
+#define YYRECOVERING() (!!yyerrstatus)
+
+#define YYBACKUP(Token, Value) \
+do \
+ if (yychar == YYEMPTY && yylen == 1) \
+ { \
+ yychar = (Token); \
+ yylval = (Value); \
+ yytoken = YYTRANSLATE (yychar); \
+ YYPOPSTACK (1); \
+ goto yybackup; \
+ } \
+ else \
+ { \
+ yyerror (]b4_yyerror_args[YY_("syntax error: cannot back up")); \
+ YYERROR; \
+ } \
+while (YYID (0))
+
+
+#define YYTERROR 1
+#define YYERRCODE 256
+
+
+/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
+ If N is 0, then set CURRENT to the empty location which ends
+ the previous symbol: RHS[0] (always defined). */
+
+#define YYRHSLOC(Rhs, K) ((Rhs)[K])
+#ifndef YYLLOC_DEFAULT
+# define YYLLOC_DEFAULT(Current, Rhs, N) \
+ do \
+ if (YYID (N)) \
+ { \
+ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
+ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
+ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \
+ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \
+ } \
+ else \
+ { \
+ (Current).first_line = (Current).last_line = \
+ YYRHSLOC (Rhs, 0).last_line; \
+ (Current).first_column = (Current).last_column = \
+ YYRHSLOC (Rhs, 0).last_column; \
+ } \
+ while (YYID (0))
+#endif
+
+
+/* YY_LOCATION_PRINT -- Print the location on the stream.
+ This macro was not mandated originally: define only if we know
+ we won't break user code: when these are the locations we know. */
+
+#ifndef YY_LOCATION_PRINT
+# if YYLTYPE_IS_TRIVIAL
+# define YY_LOCATION_PRINT(File, Loc) \
+ fprintf (File, "%d.%d-%d.%d", \
+ (Loc).first_line, (Loc).first_column, \
+ (Loc).last_line, (Loc).last_column)
+# else
+# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+# endif
+#endif
+
+
+/* YYLEX -- calling `yylex' with the right arguments. */
+
+#ifdef YYLEX_PARAM
+# define YYLEX yylex (]b4_pure_if([&yylval[]b4_locations_if([, &yylloc]), ])[YYLEX_PARAM)
+#else
+# define YYLEX ]b4_c_function_call([yylex], [int], b4_lex_param)[
+#endif
+
+/* Enable debugging if requested. */
+#if YYDEBUG
+
+# ifndef YYFPRINTF
+# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
+# define YYFPRINTF fprintf
+# endif
+
+# define YYDPRINTF(Args) \
+do { \
+ if (yydebug) \
+ YYFPRINTF Args; \
+} while (YYID (0))
+
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
+do { \
+ if (yydebug) \
+ { \
+ YYFPRINTF (stderr, "%s ", Title); \
+ yy_symbol_print (stderr, \
+ Type, Value]b4_locations_if([, Location])[]b4_user_args[); \
+ YYFPRINTF (stderr, "\n"); \
+ } \
+} while (YYID (0))
+
+]b4_yy_symbol_print_generate([b4_c_function_def])[
+
+/*------------------------------------------------------------------.
+| yy_stack_print -- Print the state stack from its BOTTOM up to its |
+| TOP (included). |
+`------------------------------------------------------------------*/
+
+]b4_c_function_def([yy_stack_print], [static void],
+ [[yytype_int16 *yybottom], [yybottom]],
+ [[yytype_int16 *yytop], [yytop]])[
+{
+ YYFPRINTF (stderr, "Stack now");
+ for (; yybottom <= yytop; yybottom++)
+ {
+ int yybot = *yybottom;
+ YYFPRINTF (stderr, " %d", yybot);
+ }
+ YYFPRINTF (stderr, "\n");
+}
+
+# define YY_STACK_PRINT(Bottom, Top) \
+do { \
+ if (yydebug) \
+ yy_stack_print ((Bottom), (Top)); \
+} while (YYID (0))
+
+
+/*------------------------------------------------.
+| Report that the YYRULE is going to be reduced. |
+`------------------------------------------------*/
+
+]b4_c_function_def([yy_reduce_print], [static void],
+ [[YYSTYPE *yyvsp], [yyvsp]],
+ b4_locations_if([[[YYLTYPE *yylsp], [yylsp]],
+ ])[[int yyrule], [yyrule]]m4_ifset([b4_parse_param], [,
+ b4_parse_param]))[
+{
+ int yynrhs = yyr2[yyrule];
+ int yyi;
+ unsigned long int yylno = yyrline[yyrule];
+ YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
+ yyrule - 1, yylno);
+ /* The symbols being reduced. */
+ for (yyi = 0; yyi < yynrhs; yyi++)
+ {
+ YYFPRINTF (stderr, " $%d = ", yyi + 1);
+ yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
+ &]b4_rhs_value(yynrhs, yyi + 1)[
+ ]b4_locations_if([, &]b4_rhs_location(yynrhs, yyi + 1))[]dnl
+ b4_user_args[);
+ YYFPRINTF (stderr, "\n");
+ }
+}
+
+# define YY_REDUCE_PRINT(Rule) \
+do { \
+ if (yydebug) \
+ yy_reduce_print (yyvsp, ]b4_locations_if([yylsp, ])[Rule]b4_user_args[); \
+} while (YYID (0))
+
+/* Nonzero means print parse trace. It is left uninitialized so that
+ multiple parsers can coexist. */
+int yydebug;
+#else /* !YYDEBUG */
+# define YYDPRINTF(Args)
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
+# define YY_STACK_PRINT(Bottom, Top)
+# define YY_REDUCE_PRINT(Rule)
+#endif /* !YYDEBUG */
+
+
+/* YYINITDEPTH -- initial size of the parser's stacks. */
+#ifndef YYINITDEPTH
+# define YYINITDEPTH ]b4_stack_depth_init[
+#endif
+
+/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
+ if the built-in stack extension method is used).
+
+ Do not make this value too large; the results are undefined if
+ YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
+ evaluated with infinite-precision integer arithmetic. */
+
+#ifndef YYMAXDEPTH
+# define YYMAXDEPTH ]b4_stack_depth_max[
+#endif
+
+
+
+#if YYERROR_VERBOSE
+
+# ifndef yystrlen
+# if defined __GLIBC__ && defined _STRING_H
+# define yystrlen strlen
+# else
+/* Return the length of YYSTR. */
+]b4_c_function_def([yystrlen], [static YYSIZE_T],
+ [[const char *yystr], [yystr]])[
+{
+ YYSIZE_T yylen;
+ for (yylen = 0; yystr[yylen]; yylen++)
+ continue;
+ return yylen;
+}
+# endif
+# endif
+
+# ifndef yystpcpy
+# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
+# define yystpcpy stpcpy
+# else
+/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
+ YYDEST. */
+]b4_c_function_def([yystpcpy], [static char *],
+ [[char *yydest], [yydest]], [[const char *yysrc], [yysrc]])[
+{
+ char *yyd = yydest;
+ const char *yys = yysrc;
+
+ while ((*yyd++ = *yys++) != '\0')
+ continue;
+
+ return yyd - 1;
+}
+# endif
+# endif
+
+# ifndef yytnamerr
+/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
+ quotes and backslashes, so that it's suitable for yyerror. The
+ heuristic is that double-quoting is unnecessary unless the string
+ contains an apostrophe, a comma, or backslash (other than
+ backslash-backslash). YYSTR is taken from yytname. If YYRES is
+ null, do not copy; instead, return the length of what the result
+ would have been. */
+static YYSIZE_T
+yytnamerr (char *yyres, const char *yystr)
+{
+ if (*yystr == '"')
+ {
+ YYSIZE_T yyn = 0;
+ char const *yyp = yystr;
+
+ for (;;)
+ switch (*++yyp)
+ {
+ case '\'':
+ case ',':
+ goto do_not_strip_quotes;
+
+ case '\\':
+ if (*++yyp != '\\')
+ goto do_not_strip_quotes;
+ /* Fall through. */
+ default:
+ if (yyres)
+ yyres[yyn] = *yyp;
+ yyn++;
+ break;
+
+ case '"':
+ if (yyres)
+ yyres[yyn] = '\0';
+ return yyn;
+ }
+ do_not_strip_quotes: ;
+ }
+
+ if (! yyres)
+ return yystrlen (yystr);
+
+ return yystpcpy (yyres, yystr) - yyres;
+}
+# endif
+
+/* Copy into YYRESULT an error message about the unexpected token
+ YYCHAR while in state YYSTATE. Return the number of bytes copied,
+ including the terminating null byte. If YYRESULT is null, do not
+ copy anything; just return the number of bytes that would be
+ copied. As a special case, return 0 if an ordinary "syntax error"
+ message will do. Return YYSIZE_MAXIMUM if overflow occurs during
+ size calculation. */
+static YYSIZE_T
+yysyntax_error (char *yyresult, int yystate, int yychar)
+{
+ int yyn = yypact[yystate];
+
+ if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
+ return 0;
+ else
+ {
+ int yytype = YYTRANSLATE (yychar);
+ YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
+ YYSIZE_T yysize = yysize0;
+ YYSIZE_T yysize1;
+ int yysize_overflow = 0;
+ enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+ int yyx;
+
+# if 0
+ /* This is so xgettext sees the translatable formats that are
+ constructed on the fly. */
+ YY_("syntax error, unexpected %s");
+ YY_("syntax error, unexpected %s, expecting %s");
+ YY_("syntax error, unexpected %s, expecting %s or %s");
+ YY_("syntax error, unexpected %s, expecting %s or %s or %s");
+ YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
+# endif
+ char *yyfmt;
+ char const *yyf;
+ static char const yyunexpected[] = "syntax error, unexpected %s";
+ static char const yyexpecting[] = ", expecting %s";
+ static char const yyor[] = " or %s";
+ char yyformat[sizeof yyunexpected
+ + sizeof yyexpecting - 1
+ + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
+ * (sizeof yyor - 1))];
+ char const *yyprefix = yyexpecting;
+
+ /* Start YYX at -YYN if negative to avoid negative indexes in
+ YYCHECK. */
+ int yyxbegin = yyn < 0 ? -yyn : 0;
+
+ /* Stay within bounds of both yycheck and yytname. */
+ int yychecklim = YYLAST - yyn + 1;
+ int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+ int yycount = 1;
+
+ yyarg[0] = yytname[yytype];
+ yyfmt = yystpcpy (yyformat, yyunexpected);
+
+ for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+ if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
+ {
+ if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+ {
+ yycount = 1;
+ yysize = yysize0;
+ yyformat[sizeof yyunexpected - 1] = '\0';
+ break;
+ }
+ yyarg[yycount++] = yytname[yyx];
+ yysize1 = yysize + yytnamerr (0, yytname[yyx]);
+ yysize_overflow |= (yysize1 < yysize);
+ yysize = yysize1;
+ yyfmt = yystpcpy (yyfmt, yyprefix);
+ yyprefix = yyor;
+ }
+
+ yyf = YY_(yyformat);
+ yysize1 = yysize + yystrlen (yyf);
+ yysize_overflow |= (yysize1 < yysize);
+ yysize = yysize1;
+
+ if (yysize_overflow)
+ return YYSIZE_MAXIMUM;
+
+ if (yyresult)
+ {
+ /* Avoid sprintf, as that infringes on the user's name space.
+ Don't have undefined behavior even if the translation
+ produced a string with the wrong number of "%s"s. */
+ char *yyp = yyresult;
+ int yyi = 0;
+ while ((*yyp = *yyf) != '\0')
+ {
+ if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
+ {
+ yyp += yytnamerr (yyp, yyarg[yyi++]);
+ yyf += 2;
+ }
+ else
+ {
+ yyp++;
+ yyf++;
+ }
+ }
+ }
+ return yysize;
+ }
+}
+#endif /* YYERROR_VERBOSE */
+
+
+]b4_yydestruct_generate([b4_c_function_def])[
+
+]b4_push_if([],
+[[/* Prevent warnings from -Wmissing-prototypes. */
+#ifdef YYPARSE_PARAM
+]b4_c_function_decl([yyparse], [int],
+ [[void *YYPARSE_PARAM], [YYPARSE_PARAM]])[
+#else /* ! YYPARSE_PARAM */
+]b4_c_function_decl([yyparse], [int], b4_parse_param)[
+#endif /* ! YYPARSE_PARAM */]])
+
+m4_divert_push([KILL])# ======================== M4 code.
+# b4_declare_scanner_communication_variables
+# ------------------------------------------
+# Declare the variables that are global, or local to YYPARSE if
+# pure-parser.
+m4_define([b4_declare_scanner_communication_variables],
+[[/* The lookahead symbol. */
+int yychar;
+
+/* The semantic value of the lookahead symbol. */
+YYSTYPE yylval;
+]b4_locations_if([[
+/* Location data for the lookahead symbol. */
+YYLTYPE yylloc;
+]])b4_pure_if([], [[
+/* Number of syntax errors so far. */
+int yynerrs;
+]])])
+
+# b4_declare_parser_state_variables
+# ---------------------------------
+# Declare all the variables that are needed to maintain the parser state
+# between calls to yypush_parse.
+m4_define([b4_declare_parser_state_variables],
+[b4_pure_if([[ /* Number of syntax errors so far. */
+ int yynerrs;
+]])[
+ int yystate;
+ /* Number of tokens to shift before error messages enabled. */
+ int yyerrstatus;
+
+ /* The stacks and their tools:
+ `yyss': related to states.
+ `yyvs': related to semantic values.]b4_locations_if([[
+ `yyls': related to locations.]])[
+
+ Refer to the stacks thru separate pointers, to allow yyoverflow
+ to reallocate them elsewhere. */
+
+ /* The state stack. */
+ yytype_int16 yyssa[YYINITDEPTH];
+ yytype_int16 *yyss;
+ yytype_int16 *yyssp;
+
+ /* The semantic value stack. */
+ YYSTYPE yyvsa[YYINITDEPTH];
+ YYSTYPE *yyvs;
+ YYSTYPE *yyvsp;
+]b4_locations_if([[
+ /* The location stack. */
+ YYLTYPE yylsa[YYINITDEPTH];
+ YYLTYPE *yyls;
+ YYLTYPE *yylsp;
+
+ /* The locations where the error started and ended. */
+ YYLTYPE yyerror_range[2];
+]])[
+ YYSIZE_T yystacksize;
+]])
+
+m4_divert_pop([KILL])dnl# ====================== End of M4 code.
+
+b4_pure_if([], [b4_declare_scanner_communication_variables])
+
+b4_push_if(
+[[struct yypstate
+ {
+ ]b4_declare_parser_state_variables[
+ /* Used to determine if this is the first time this instance has
+ been used. */
+ int yynew;
+ };]b4_pure_if([], [[
+
+static char yypstate_allocated = 0;]])b4_pull_if([
+
+b4_c_function_def([[yyparse]], [[int]], b4_parse_param)[
+{
+ return yypull_parse (0]m4_ifset([b4_parse_param],
+ [[, ]b4_c_args(b4_parse_param)])[);
+}
+
+]b4_c_function_def([[yypull_parse]], [[int]],
+ [[[yypstate *yyps]], [[yyps]]]m4_ifset([b4_parse_param], [,
+ b4_parse_param]))[
+{
+ int yystatus;
+ yypstate *yyps_local;]b4_pure_if([[
+ int yychar;
+ YYSTYPE yylval;]b4_locations_if([[
+ YYLTYPE yylloc;]])])[
+ if (yyps == 0)
+ {
+ yyps_local = yypstate_new ();
+ if (!yyps_local)
+ {]b4_pure_if([[
+ yyerror (]b4_yyerror_args[YY_("memory exhausted"));]], [[
+ if (!yypstate_allocated)
+ yyerror (]b4_yyerror_args[YY_("memory exhausted"));]])[
+ return 2;
+ }
+ }
+ else
+ yyps_local = yyps;
+ do {
+ yychar = YYLEX;
+ yystatus =
+ yypush_parse (yyps_local]b4_pure_if([[, yychar, &yylval]b4_locations_if([[, &yylloc]])])m4_ifset([b4_parse_param], [, b4_c_args(b4_parse_param)])[);
+ } while (yystatus == YYPUSH_MORE);
+ if (yyps == 0)
+ yypstate_delete (yyps_local);
+ return yystatus;
+}]])[
+
+/* Initialize the parser data structure. */
+]b4_c_function_def([[yypstate_new]], [[yypstate *]])[
+{
+ yypstate *yyps;]b4_pure_if([], [[
+ if (yypstate_allocated)
+ return 0;]])[
+ yyps = (yypstate *) malloc (sizeof *yyps);
+ if (!yyps)
+ return 0;
+ yyps->yynew = 1;]b4_pure_if([], [[
+ yypstate_allocated = 1;]])[
+ return yyps;
+}
+
+]b4_c_function_def([[yypstate_delete]], [[void]],
+ [[[yypstate *yyps]], [[yyps]]])[
+{
+#ifndef yyoverflow
+ /* If the stack was reallocated but the parse did not complete, then the
+ stack still needs to be freed. */
+ if (!yyps->yynew && yyps->yyss != yyps->yyssa)
+ YYSTACK_FREE (yyps->yyss);
+#endif
+ free (yyps);]b4_pure_if([], [[
+ yypstate_allocated = 0;]])[
+}
+
+]b4_pure_if([[#define ]b4_prefix[nerrs yyps->]b4_prefix[nerrs
+]])[#define yystate yyps->yystate
+#define yyerrstatus yyps->yyerrstatus
+#define yyssa yyps->yyssa
+#define yyss yyps->yyss
+#define yyssp yyps->yyssp
+#define yyvsa yyps->yyvsa
+#define yyvs yyps->yyvs
+#define yyvsp yyps->yyvsp
+]b4_locations_if([[#define yylsa yyps->yylsa
+#define yyls yyps->yyls
+#define yylsp yyps->yylsp
+#define yyerror_range yyps->yyerror_range
+]])[#define yystacksize yyps->yystacksize
+]])[
+/*-------------------------.
+| yyparse or yypush_parse. |
+`-------------------------*/
+]b4_push_if([
+b4_c_function_def([[yypush_parse]], [[int]],
+ [[[yypstate *yyps]], [[yyps]]]b4_pure_if([,
+ [[[int yypushed_char]], [[yypushed_char]]],
+ [[[YYSTYPE const *yypushed_val]], [[yypushed_val]]]b4_locations_if([,
+ [[[YYLTYPE const *yypushed_loc]], [[yypushed_loc]]]])])m4_ifset([b4_parse_param], [,
+ b4_parse_param]))], [
+#ifdef YYPARSE_PARAM
+b4_c_function_def([yyparse], [int], [[void *YYPARSE_PARAM], [YYPARSE_PARAM]])
+#else /* ! YYPARSE_PARAM */
+b4_c_function_def([yyparse], [int], b4_parse_param)
+#endif])[
+{
+]b4_pure_if([b4_declare_scanner_communication_variables])
+b4_push_if([b4_pure_if([], [[ int yypushed_char = yychar;
+ YYSTYPE yypushed_val = yylval;
+ ]b4_locations_if([[YYLTYPE yypushed_loc = yylloc;
+]])])],
+ [b4_declare_parser_state_variables])[
+ int yyn;
+ int yyresult;
+ /* Lookahead token as an internal (translated) token number. */
+ int yytoken;
+ /* The variables used to return semantic value and location from the
+ action routines. */
+ YYSTYPE yyval;]b4_locations_if([[
+ YYLTYPE yyloc;]])[
+
+#if YYERROR_VERBOSE
+ /* Buffer for error messages, and its allocated size. */
+ char yymsgbuf[128];
+ char *yymsg = yymsgbuf;
+ YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
+#endif
+
+#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)]b4_locations_if([, yylsp -= (N)])[)
+
+ /* The number of symbols on the RHS of the reduced rule.
+ Keep to zero when no symbol should be popped. */
+ int yylen = 0;]b4_push_if([[
+
+ if (!yyps->yynew)
+ {
+ yyn = yypact[yystate];
+ goto yyread_pushed_token;
+ }]])[
+
+ yytoken = 0;
+ yyss = yyssa;
+ yyvs = yyvsa;]b4_locations_if([[
+ yyls = yylsa;]])[
+ yystacksize = YYINITDEPTH;
+
+ YYDPRINTF ((stderr, "Starting parse\n"));
+
+ yystate = 0;
+ yyerrstatus = 0;
+ yynerrs = 0;
+ yychar = YYEMPTY; /* Cause a token to be read. */
+
+ /* Initialize stack pointers.
+ Waste one element of value and location stack
+ so that they stay on the same level as the state stack.
+ The wasted elements are never initialized. */
+ yyssp = yyss;
+ yyvsp = yyvs;]b4_locations_if([[
+ yylsp = yyls;
+
+#if YYLTYPE_IS_TRIVIAL
+ /* Initialize the default location before parsing starts. */
+ yylloc.first_line = yylloc.last_line = ]b4_location_initial_line[;
+ yylloc.first_column = yylloc.last_column = ]b4_location_initial_column[;
+#endif]])
+m4_ifdef([b4_initial_action],[
+m4_pushdef([b4_at_dollar], [m4_define([b4_at_dollar_used])yylloc])dnl
+m4_pushdef([b4_dollar_dollar], [m4_define([b4_dollar_dollar_used])yylval])dnl
+/* User initialization code. */
+b4_user_initial_action
+m4_popdef([b4_dollar_dollar])dnl
+m4_popdef([b4_at_dollar])])dnl
+m4_ifdef([b4_dollar_dollar_used],[[ yyvsp[0] = yylval;
+]])dnl
+m4_ifdef([b4_at_dollar_used], [[ yylsp[0] = yylloc;
+]])[
+ goto yysetstate;
+
+/*------------------------------------------------------------.
+| yynewstate -- Push a new state, which is found in yystate. |
+`------------------------------------------------------------*/
+ yynewstate:
+ /* In all cases, when you get here, the value and location stacks
+ have just been pushed. So pushing a state here evens the stacks. */
+ yyssp++;
+
+ yysetstate:
+ *yyssp = yystate;
+
+ if (yyss + yystacksize - 1 <= yyssp)
+ {
+ /* Get the current used size of the three stacks, in elements. */
+ YYSIZE_T yysize = yyssp - yyss + 1;
+
+#ifdef yyoverflow
+ {
+ /* Give user a chance to reallocate the stack. Use copies of
+ these so that the &'s don't force the real ones into
+ memory. */
+ YYSTYPE *yyvs1 = yyvs;
+ yytype_int16 *yyss1 = yyss;]b4_locations_if([
+ YYLTYPE *yyls1 = yyls;])[
+
+ /* Each stack pointer address is followed by the size of the
+ data in use in that stack, in bytes. This used to be a
+ conditional around just the two extra args, but that might
+ be undefined if yyoverflow is a macro. */
+ yyoverflow (YY_("memory exhausted"),
+ &yyss1, yysize * sizeof (*yyssp),
+ &yyvs1, yysize * sizeof (*yyvsp),]b4_locations_if([
+ &yyls1, yysize * sizeof (*yylsp),])[
+ &yystacksize);
+]b4_locations_if([
+ yyls = yyls1;])[
+ yyss = yyss1;
+ yyvs = yyvs1;
+ }
+#else /* no yyoverflow */
+# ifndef YYSTACK_RELOCATE
+ goto yyexhaustedlab;
+# else
+ /* Extend the stack our own way. */
+ if (YYMAXDEPTH <= yystacksize)
+ goto yyexhaustedlab;
+ yystacksize *= 2;
+ if (YYMAXDEPTH < yystacksize)
+ yystacksize = YYMAXDEPTH;
+
+ {
+ yytype_int16 *yyss1 = yyss;
+ union yyalloc *yyptr =
+ (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+ if (! yyptr)
+ goto yyexhaustedlab;
+ YYSTACK_RELOCATE (yyss_alloc, yyss);
+ YYSTACK_RELOCATE (yyvs_alloc, yyvs);]b4_locations_if([
+ YYSTACK_RELOCATE (yyls_alloc, yyls);])[
+# undef YYSTACK_RELOCATE
+ if (yyss1 != yyssa)
+ YYSTACK_FREE (yyss1);
+ }
+# endif
+#endif /* no yyoverflow */
+
+ yyssp = yyss + yysize - 1;
+ yyvsp = yyvs + yysize - 1;]b4_locations_if([
+ yylsp = yyls + yysize - 1;])[
+
+ YYDPRINTF ((stderr, "Stack size increased to %lu\n",
+ (unsigned long int) yystacksize));
+
+ if (yyss + yystacksize - 1 <= yyssp)
+ YYABORT;
+ }
+
+ YYDPRINTF ((stderr, "Entering state %d\n", yystate));
+
+ if (yystate == YYFINAL)
+ YYACCEPT;
+
+ goto yybackup;
+
+/*-----------.
+| yybackup. |
+`-----------*/
+yybackup:
+
+ /* Do appropriate processing given the current state. Read a
+ lookahead token if we need one and don't already have one. */
+
+ /* First try to decide what to do without reference to lookahead token. */
+ yyn = yypact[yystate];
+ if (yyn == YYPACT_NINF)
+ goto yydefault;
+
+ /* Not known => get a lookahead token if don't already have one. */
+
+ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
+ if (yychar == YYEMPTY)
+ {]b4_push_if([[
+ if (!yyps->yynew)
+ {]b4_use_push_for_pull_if([], [[
+ YYDPRINTF ((stderr, "Return for a new token:\n"));]])[
+ yyresult = YYPUSH_MORE;
+ goto yypushreturn;
+ }
+ yyps->yynew = 0;]b4_pure_if([], [[
+ /* Restoring the pushed token is only necessary for the first
+ yypush_parse invocation since subsequent invocations don't overwrite
+ it before jumping to yyread_pushed_token. */
+ yychar = yypushed_char;
+ yylval = yypushed_val;]b4_locations_if([[
+ yylloc = yypushed_loc;]])])[
+yyread_pushed_token:]])[
+ YYDPRINTF ((stderr, "Reading a token: "));]b4_push_if([b4_pure_if([[
+ yychar = yypushed_char;
+ if (yypushed_val)
+ yylval = *yypushed_val;]b4_locations_if([[
+ if (yypushed_loc)
+ yylloc = *yypushed_loc;]])])], [[
+ yychar = YYLEX;]])[
+ }
+
+ if (yychar <= YYEOF)
+ {
+ yychar = yytoken = YYEOF;
+ YYDPRINTF ((stderr, "Now at end of input.\n"));
+ }
+ else
+ {
+ yytoken = YYTRANSLATE (yychar);
+ YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
+ }
+
+ /* If the proper action on seeing token YYTOKEN is to reduce or to
+ detect an error, take that action. */
+ yyn += yytoken;
+ if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
+ goto yydefault;
+ yyn = yytable[yyn];
+ if (yyn <= 0)
+ {
+ if (yyn == 0 || yyn == YYTABLE_NINF)
+ goto yyerrlab;
+ yyn = -yyn;
+ goto yyreduce;
+ }
+
+ /* Count tokens shifted since error; after three, turn off error
+ status. */
+ if (yyerrstatus)
+ yyerrstatus--;
+
+ /* Shift the lookahead token. */
+ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
+
+ /* Discard the shifted token. */
+ yychar = YYEMPTY;
+
+ yystate = yyn;
+ *++yyvsp = yylval;
+]b4_locations_if([ *++yylsp = yylloc;])[
+ goto yynewstate;
+
+
+/*-----------------------------------------------------------.
+| yydefault -- do the default action for the current state. |
+`-----------------------------------------------------------*/
+yydefault:
+ yyn = yydefact[yystate];
+ if (yyn == 0)
+ goto yyerrlab;
+ goto yyreduce;
+
+
+/*-----------------------------.
+| yyreduce -- Do a reduction. |
+`-----------------------------*/
+yyreduce:
+ /* yyn is the number of a rule to reduce with. */
+ yylen = yyr2[yyn];
+
+ /* If YYLEN is nonzero, implement the default value of the action:
+ `$$ = $1'.
+
+ Otherwise, the following line sets YYVAL to garbage.
+ This behavior is undocumented and Bison
+ users should not rely upon it. Assigning to YYVAL
+ unconditionally makes the parser a bit smaller, and it avoids a
+ GCC warning that YYVAL may be used uninitialized. */
+ yyval = yyvsp[1-yylen];
+
+]b4_locations_if(
+[[ /* Default location. */
+ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen);]])[
+ YY_REDUCE_PRINT (yyn);
+ switch (yyn)
+ {
+ ]b4_user_actions[
+ default: break;
+ }
+ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
+
+ YYPOPSTACK (yylen);
+ yylen = 0;
+ YY_STACK_PRINT (yyss, yyssp);
+
+ *++yyvsp = yyval;]b4_locations_if([
+ *++yylsp = yyloc;])[
+
+ /* Now `shift' the result of the reduction. Determine what state
+ that goes to, based on the state we popped back to and the rule
+ number reduced by. */
+
+ yyn = yyr1[yyn];
+
+ yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
+ if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
+ yystate = yytable[yystate];
+ else
+ yystate = yydefgoto[yyn - YYNTOKENS];
+
+ goto yynewstate;
+
+
+/*------------------------------------.
+| yyerrlab -- here on detecting error |
+`------------------------------------*/
+yyerrlab:
+ /* If not already recovering from an error, report this error. */
+ if (!yyerrstatus)
+ {
+ ++yynerrs;
+#if ! YYERROR_VERBOSE
+ yyerror (]b4_yyerror_args[YY_("syntax error"));
+#else
+ {
+ YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
+ if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
+ {
+ YYSIZE_T yyalloc = 2 * yysize;
+ if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
+ yyalloc = YYSTACK_ALLOC_MAXIMUM;
+ if (yymsg != yymsgbuf)
+ YYSTACK_FREE (yymsg);
+ yymsg = (char *) YYSTACK_ALLOC (yyalloc);
+ if (yymsg)
+ yymsg_alloc = yyalloc;
+ else
+ {
+ yymsg = yymsgbuf;
+ yymsg_alloc = sizeof yymsgbuf;
+ }
+ }
+
+ if (0 < yysize && yysize <= yymsg_alloc)
+ {
+ (void) yysyntax_error (yymsg, yystate, yychar);
+ yyerror (]b4_yyerror_args[yymsg);
+ }
+ else
+ {
+ yyerror (]b4_yyerror_args[YY_("syntax error"));
+ if (yysize != 0)
+ goto yyexhaustedlab;
+ }
+ }
+#endif
+ }
+
+]b4_locations_if([[ yyerror_range[0] = yylloc;]])[
+
+ if (yyerrstatus == 3)
+ {
+ /* If just tried and failed to reuse lookahead token after an
+ error, discard it. */
+
+ if (yychar <= YYEOF)
+ {
+ /* Return failure if at end of input. */
+ if (yychar == YYEOF)
+ YYABORT;
+ }
+ else
+ {
+ yydestruct ("Error: discarding",
+ yytoken, &yylval]b4_locations_if([, &yylloc])[]b4_user_args[);
+ yychar = YYEMPTY;
+ }
+ }
+
+ /* Else will try to reuse lookahead token after shifting the error
+ token. */
+ goto yyerrlab1;
+
+
+/*---------------------------------------------------.
+| yyerrorlab -- error raised explicitly by YYERROR. |
+`---------------------------------------------------*/
+yyerrorlab:
+
+ /* Pacify compilers like GCC when the user code never invokes
+ YYERROR and the label yyerrorlab therefore never appears in user
+ code. */
+ if (/*CONSTCOND*/ 0)
+ goto yyerrorlab;
+
+]b4_locations_if([[ yyerror_range[0] = yylsp[1-yylen];
+]])[ /* Do not reclaim the symbols of the rule which action triggered
+ this YYERROR. */
+ YYPOPSTACK (yylen);
+ yylen = 0;
+ YY_STACK_PRINT (yyss, yyssp);
+ yystate = *yyssp;
+ goto yyerrlab1;
+
+
+/*-------------------------------------------------------------.
+| yyerrlab1 -- common code for both syntax error and YYERROR. |
+`-------------------------------------------------------------*/
+yyerrlab1:
+ yyerrstatus = 3; /* Each real token shifted decrements this. */
+
+ for (;;)
+ {
+ yyn = yypact[yystate];
+ if (yyn != YYPACT_NINF)
+ {
+ yyn += YYTERROR;
+ if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+ {
+ yyn = yytable[yyn];
+ if (0 < yyn)
+ break;
+ }
+ }
+
+ /* Pop the current state because it cannot handle the error token. */
+ if (yyssp == yyss)
+ YYABORT;
+
+]b4_locations_if([[ yyerror_range[0] = *yylsp;]])[
+ yydestruct ("Error: popping",
+ yystos[yystate], yyvsp]b4_locations_if([, yylsp])[]b4_user_args[);
+ YYPOPSTACK (1);
+ yystate = *yyssp;
+ YY_STACK_PRINT (yyss, yyssp);
+ }
+
+ *++yyvsp = yylval;
+]b4_locations_if([[
+ yyerror_range[1] = yylloc;
+ /* Using YYLLOC is tempting, but would change the location of
+ the lookahead. YYLOC is available though. */
+ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2);
+ *++yylsp = yyloc;]])[
+
+ /* Shift the error token. */
+ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
+
+ yystate = yyn;
+ goto yynewstate;
+
+
+/*-------------------------------------.
+| yyacceptlab -- YYACCEPT comes here. |
+`-------------------------------------*/
+yyacceptlab:
+ yyresult = 0;
+ goto yyreturn;
+
+/*-----------------------------------.
+| yyabortlab -- YYABORT comes here. |
+`-----------------------------------*/
+yyabortlab:
+ yyresult = 1;
+ goto yyreturn;
+
+#if !defined(yyoverflow) || YYERROR_VERBOSE
+/*-------------------------------------------------.
+| yyexhaustedlab -- memory exhaustion comes here. |
+`-------------------------------------------------*/
+yyexhaustedlab:
+ yyerror (]b4_yyerror_args[YY_("memory exhausted"));
+ yyresult = 2;
+ /* Fall through. */
+#endif
+
+yyreturn:
+ if (yychar != YYEMPTY)
+ yydestruct ("Cleanup: discarding lookahead",
+ yytoken, &yylval]b4_locations_if([, &yylloc])[]b4_user_args[);
+ /* Do not reclaim the symbols of the rule which action triggered
+ this YYABORT or YYACCEPT. */
+ YYPOPSTACK (yylen);
+ YY_STACK_PRINT (yyss, yyssp);
+ while (yyssp != yyss)
+ {
+ yydestruct ("Cleanup: popping",
+ yystos[*yyssp], yyvsp]b4_locations_if([, yylsp])[]b4_user_args[);
+ YYPOPSTACK (1);
+ }
+#ifndef yyoverflow
+ if (yyss != yyssa)
+ YYSTACK_FREE (yyss);
+#endif
+]b4_push_if([[ yyps->yynew = 1;
+
+yypushreturn:
+]])[#if YYERROR_VERBOSE
+ if (yymsg != yymsgbuf)
+ YYSTACK_FREE (yymsg);
+#endif
+ /* Make sure YYID is used. */
+ return YYID (yyresult);
+}
+
+
+]b4_epilogue
+b4_defines_if(
+[@output(b4_spec_defines_file@)
+b4_copyright([Skeleton interface for Bison's Yacc-like parsers in C],dnl '
+ [1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006])
+
+b4_percent_code_get([[requires]])[]dnl
+
+b4_token_enums_defines(b4_tokens)
+
+[#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
+]m4_ifdef([b4_stype],
+[[typedef union ]b4_union_name[
+{
+]b4_user_stype[
+} YYSTYPE;
+# define YYSTYPE_IS_TRIVIAL 1]],
+[m4_if(b4_tag_seen_flag, 0,
+[[typedef int YYSTYPE;
+# define YYSTYPE_IS_TRIVIAL 1]])])[
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+#endif
+
+]b4_pure_if([], [[extern YYSTYPE ]b4_prefix[lval;]])
+
+b4_locations_if(
+[#if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED
+typedef struct YYLTYPE
+{
+ int first_line;
+ int first_column;
+ int last_line;
+ int last_column;
+} YYLTYPE;
+# define yyltype YYLTYPE /* obsolescent; will be withdrawn */
+# define YYLTYPE_IS_DECLARED 1
+# define YYLTYPE_IS_TRIVIAL 1
+#endif
+
+]b4_pure_if([], [[extern YYLTYPE ]b4_prefix[lloc;]])
+)dnl b4_locations_if
+b4_push_if([[
+#ifndef YYPUSH_DECLS
+# define YYPUSH_DECLS
+struct ]b4_prefix[pstate;
+typedef struct ]b4_prefix[pstate ]b4_prefix[pstate;
+enum { YYPUSH_MORE = 4 };
+]b4_pull_if([b4_c_function_decl([b4_prefix[parse]], [[int]], b4_parse_param)
+])b4_c_function_decl([b4_prefix[push_parse]], [[int]],
+ [[b4_prefix[pstate *yyps]], [[yyps]]]b4_pure_if([,
+ [[[int yypushed_char]], [[yypushed_char]]],
+ [[[YYSTYPE const *yypushed_val]], [[yypushed_val]]]b4_locations_if([,
+ [[[YYLTYPE const *yypushed_loc]], [[yypushed_loc]]]])])m4_ifset([b4_parse_param], [,
+ b4_parse_param]))
+b4_pull_if([b4_c_function_decl([b4_prefix[pull_parse]], [[int]],
+ [[b4_prefix[pstate *yyps]], [[yyps]]]m4_ifset([b4_parse_param], [,
+ b4_parse_param]))])
+b4_c_function_decl([b4_prefix[pstate_new]], [b4_prefix[pstate *]],
+ [[[void]], []])
+b4_c_function_decl([b4_prefix[pstate_delete]], [[void]],
+ [[b4_prefix[pstate *yyps]], [[yyps]]])[
+#endif
+]])
+b4_percent_code_get([[provides]])[]dnl
+])dnl b4_defines_if
+m4_divert_pop(0)
diff --git a/tools/mhmake/src/build.cpp b/tools/mhmake/src/build.cpp
new file mode 100644
index 000000000..ee79ad4f6
--- /dev/null
+++ b/tools/mhmake/src/build.cpp
@@ -0,0 +1,1683 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+
+#include "mhmakefileparser.h"
+#include "rule.h"
+#include "util.h"
+
+/*****************************************************************************/
+int mhmakefileparser::SearchPath(const char *szCommand, const char *pExt, size_t Len, char *szFullCommand,char **pFilePart) const
+{
+ static vector< fileinfo* > vSearchPath;
+
+ string Command(szCommand);
+ if (pExt)
+ Command+=pExt;
+ vector< fileinfo* >::iterator It;
+ vector< fileinfo* >::iterator ItEnd;
+
+ fileinfo* pCommandFile=GetFileInfo(Command,m_MakeDir);
+ if (pCommandFile->Exists())
+ {
+ goto found;
+ }
+ pCommandFile->InvalidateDate(); // It could be created in the makefile later
+ if (!vSearchPath.size())
+ {
+ char *pPath=getenv(PATH);
+ if (!pPath)
+ return 0;
+ char *Path=strdup(pPath); // To be able to use strtok
+ char *pTok=strtok(Path,OSPATHENVSEPSTR);
+ while (pTok)
+ {
+ vSearchPath.push_back(GetFileInfo(pTok,m_MakeDir));
+ pTok=strtok(NULL,OSPATHENVSEPSTR);
+ }
+ free(Path);
+ }
+ It=vSearchPath.begin();
+ ItEnd=vSearchPath.end();
+ while (It!=ItEnd)
+ {
+ pCommandFile=GetFileInfo(Command,*It);
+ if (pCommandFile->Exists())
+ goto found;
+ It++;
+ }
+
+ return 0;
+
+found:
+ string FullCommand=pCommandFile->GetFullFileName();
+ size_t CommandLen=FullCommand.size();
+ if (CommandLen>Len-1)
+ {
+ throw string("Command to long: ") + FullCommand;
+ }
+ strcpy(szFullCommand,FullCommand.c_str());
+ return 1;
+}
+
+/*****************************************************************************/
+string mhmakefileparser::SearchCommand(const string &Command, const string &Extension) const
+{
+ char FullCommand[MAX_PATH]="";
+ unsigned long Size=sizeof(FullCommand);
+ const char *pExt;
+ if (Extension.empty())
+ pExt=NULL;
+ else
+ pExt=Extension.c_str();
+ if (SearchPath(UnquoteFileName(Command).c_str(),pExt,MAX_PATH,FullCommand,NULL))
+ return FullCommand;
+#ifdef WIN32
+ /* See if we have a path for python.exe in the registry */
+ HKEY hKey;
+ string RegEntry=Command;
+ if (pExt)
+ {
+ RegEntry+=Extension;
+ }
+ string KeyName=string("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\")+RegEntry;
+ if (ERROR_SUCCESS!=RegOpenKey(HKEY_LOCAL_MACHINE,KeyName.c_str(),&hKey))
+ return FullCommand;
+
+ RegQueryValueEx(hKey,NULL,NULL,NULL,(LPBYTE)FullCommand,&Size);
+
+ RegCloseKey(hKey);
+#endif
+
+ return FullCommand;
+}
+
+/*****************************************************************************/
+/* Deletes a complete directory or files with wildcard. It can be assumed that the Directory passed does exist */
+static bool DeleteDir(const string &Dir,const string WildSearch="*",bool bRemoveDir=true)
+{
+ bool Error=false;
+ string Pattern=Dir+OSPATHSEP+WildSearch;
+#ifdef WIN32
+ WIN32_FIND_DATA FindData;
+ mh_pid_t hFind=FindFirstFile(Pattern.c_str(),&FindData);
+ if (hFind==INVALID_HANDLE_VALUE)
+ {
+ return Error;
+ }
+
+ do
+ {
+ /* Only handle items which are not . and .. */
+ if (FindData.cFileName[0]!='.' || (FindData.cFileName[1] && (FindData.cFileName[1]!='.' || FindData.cFileName[2])) )
+ {
+ string FileName=Dir+OSPATHSEP+FindData.cFileName;
+ if (FindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
+ {
+ Error = DeleteDir(FileName);
+ }
+ else
+ {
+ Error = (-1==remove(FileName.c_str()));
+ }
+ }
+ } while (FindNextFile(hFind,&FindData));
+
+ FindClose(hFind);
+
+ if (bRemoveDir)
+ Error = (0==RemoveDirectory(Dir.c_str()));
+#else
+ glob_t Res;
+ if (glob (Pattern.c_str(), GLOB_ERR|GLOB_NOSORT|GLOB_MARK, NULL, &Res))
+ return Error;
+
+ for (int i=0; i<Res.gl_pathc; i++)
+ {
+ int Len=strlen(Res.gl_pathv[i])-1;
+ if (Res.gl_pathv[i][Len]=='/')
+ {
+ Res.gl_pathv[i][Len]=0;
+ Error = DeleteDir(Res.gl_pathv[i]);
+ }
+ else
+ {
+ Error = (-1==remove(Res.gl_pathv[i]));
+ }
+ }
+
+ globfree(&Res);
+
+ if (bRemoveDir)
+ Error = (-1==remove(Dir.c_str()));
+#endif
+
+ return Error;
+}
+
+/*****************************************************************************/
+mh_pid_t mhmakefileparser::DeleteFiles(const string &Params) const
+{
+ bool IgnoreError=false;
+ vector<fileinfo*> Files;
+
+ // First check if the first parameter is -e meaning don't give an error when file does not exist
+ if (Params[1]=='-')
+ {
+ if (Params[2]=='e')
+ {
+ IgnoreError=true;
+ SplitToItems(Params.substr(4),Files);
+ }
+ else
+ {
+ cerr << "Invalid option "<<Params[1]<<" in del statement\n";
+ return (mh_pid_t)-1;
+ }
+ }
+ else
+ {
+ SplitToItems(Params,Files);
+ }
+
+ vector<fileinfo*>::const_iterator It=Files.begin();
+ while (It!=Files.end())
+ {
+ fileinfo* pFile=*It++;
+ string DirSearch="*";
+ bool bRemoveDir=true;
+
+ /* Now check if there is a wildcard */
+ if (pFile->GetFullFileName().find('*')!=string::npos)
+ {
+ DirSearch=pFile->GetName();
+ pFile=pFile->GetDir();
+ bRemoveDir=false;
+ }
+
+ pFile->InvalidateDate();
+ if (IgnoreError && !pFile->Exists() && !pFile->IsDir())
+ {
+ continue;
+ }
+
+ const string &FileName=pFile->GetFullFileName();
+ if (pFile->IsDir())
+ {
+ if (DeleteDir(FileName,DirSearch,bRemoveDir) && !IgnoreError)
+ {
+ cerr << "Error deleting "<<FileName<<endl;
+ return (mh_pid_t)-1;
+ }
+ }
+ else
+ {
+ if (-1==remove(FileName.c_str()) && !IgnoreError)
+ {
+ cerr << "Error deleting "<<FileName<<endl;
+ return (mh_pid_t)-1;
+ }
+ }
+ }
+ return (mh_pid_t)0;
+}
+
+/*****************************************************************************/
+/* pDest can be a directory or a file */
+static bool CopyFile(fileinfo* pSrc, fileinfo* pDest)
+{
+ if (pDest->IsDir())
+ {
+ pDest=GetFileInfo(pSrc->GetName(),pDest);
+ }
+ string SrcFileName=pSrc->GetFullFileName();
+ string DestFileName=pDest->GetFullFileName();
+
+ /* Now copy the file */
+ FILE *pSrcFile=fopen(SrcFileName.c_str(),"rb");
+ if (!pSrcFile)
+ {
+ cerr << "copy: error opening file "<<SrcFileName<<endl;
+ return false;
+ }
+ FILE *pDestFile=fopen(DestFileName.c_str(),"wb");
+ if (!pDestFile)
+ {
+ cerr << "copy: error creating file "<<DestFileName<<endl;
+ return false;
+ }
+ char Buf[4096];
+ size_t Ret;
+
+ while ( (Ret=fread(Buf,1,sizeof(Buf),pSrcFile)) > 0)
+ {
+ fwrite(Buf,1,Ret,pDestFile);
+ }
+ fclose(pSrcFile);
+ fclose(pDestFile);
+ pDest->InvalidateDate();
+ return true;
+}
+
+/*****************************************************************************/
+/* Copies a complete directory to a destination (currenlty not recursive */
+static bool CopyDir(fileinfo* pDir, fileinfo* pDest,const string WildSearch="*")
+{
+ bool Error=true;
+ string Pattern=pDir->GetFullFileName()+OSPATHSEP+WildSearch;
+#ifdef WIN32
+ WIN32_FIND_DATA FindData;
+ mh_pid_t hFind=FindFirstFile(Pattern.c_str(),&FindData);
+ if (hFind==INVALID_HANDLE_VALUE)
+ {
+ return false;
+ }
+
+ do
+ {
+ /* Only handle items which are not . and .. */
+ if (FindData.cFileName[0]!='.' || (FindData.cFileName[1] && (FindData.cFileName[1]!='.' || FindData.cFileName[2])) )
+ {
+ if (FindData.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN)
+ continue;
+ fileinfo* pSrc=GetFileInfo(FindData.cFileName,pDir);
+
+ if (pSrc->IsDir())
+ {
+ fileinfo* pNewDest=GetFileInfo(FindData.cFileName,pDest);
+ if (!pNewDest->IsDir())
+ {
+ if (pNewDest->Exists())
+ {
+ cerr << pNewDest->GetFullFileName() << " exists and is not a directory.\n";
+ Error = false;
+ goto exit;
+ }
+ if (!CreateDirectory(pNewDest->GetFullFileName().c_str(),NULL))
+ {
+ cerr << "Error creating directory " << pNewDest->GetFullFileName() << endl;
+ Error = false;
+ goto exit;
+ }
+ pNewDest->InvalidateDate();
+ }
+ Error = CopyDir(pSrc,pNewDest);
+ if (!Error) goto exit;
+ }
+ else
+ {
+ Error = CopyFile(pSrc,pDest);
+ if (!Error) goto exit;
+ }
+ }
+ } while (FindNextFile(hFind,&FindData));
+
+exit:
+ FindClose(hFind);
+#else
+ glob_t Res;
+ if (glob (Pattern.c_str(), GLOB_ERR|GLOB_NOSORT|GLOB_MARK, NULL, &Res))
+ return Error;
+
+ for (int i=0; i<Res.gl_pathc; i++)
+ {
+ fileinfo* pSrc=GetFileInfo(Res.gl_pathv[i],pDir);
+ if (pSrc->IsDir())
+ {
+ *(strrchr(Res.gl_pathv[i],'/'))='\0';
+ const char *SrcDirName=strrchr(Res.gl_pathv[i],'/')+1;
+
+ if (SrcDirName[0]=='.')
+ continue;
+
+ fileinfo* pNewDest=GetFileInfo(SrcDirName,pDest);
+ if (!pNewDest->IsDir())
+ {
+ if (pNewDest->Exists())
+ {
+ cerr << pNewDest->GetQuotedFullFileName() << " exists and is not a directory.\n";
+ Error = false;
+ goto exit;
+ }
+ struct stat statbuf;
+ if ( (-1==stat(pDest->GetFullFileName().c_str(),&statbuf)) ||
+ (-1==mkdir(pNewDest->GetFullFileName().c_str(),statbuf.st_mode))
+ )
+ {
+ cerr << "Error creating directory " << pNewDest->GetQuotedFullFileName() << endl;
+ Error = false;
+ goto exit;
+ }
+ pNewDest->InvalidateDate();
+ }
+ Error = CopyDir(pSrc,pNewDest);
+ if (!Error) goto exit;
+ }
+ else
+ {
+ Error = CopyFile(GetFileInfo(Res.gl_pathv[i],pDir),pDest);
+ if (!Error) goto exit;
+ }
+ }
+
+exit:
+ globfree(&Res);
+#endif
+
+ return Error;
+}
+
+/*****************************************************************************/
+mh_pid_t mhmakefileparser::MakeDirsCommand(const string &Params) const
+{
+ vector<fileinfo*> Dirs;
+
+ SplitToItems(Params,Dirs);
+
+ size_t NrDirs=Dirs.size();
+ for (size_t i=0; i<NrDirs; i++)
+ {
+ fileinfo* pDir=Dirs[i];
+ if (pDir->GetName()=="-p")
+ continue;
+ if (!MakeDirs(pDir))
+ return (mh_pid_t)-1;
+ }
+ return (mh_pid_t)0;
+}
+
+/*****************************************************************************/
+static string RemoveQuotes(const string &StrIn)
+{
+ char FirstChar=StrIn[0];
+ string Ret=StrIn;
+ if (FirstChar=='"')
+ {
+ int Len=Ret.length()-1;
+ if (Ret[Len]=='"')
+ Ret=Ret.substr(1,Len-1);
+ }
+ else if (FirstChar=='\'')
+ {
+ int Len=Ret.length()-1;
+ if (Ret[Len]=='\'')
+ Ret=Ret.substr(1,Len-1);
+ }
+ return Ret;
+}
+mh_pid_t mhmakefileparser::EchoCommand(const string &ParamsIn) const
+{
+ string Params=f_strip(ParamsIn);
+ // Find the first > character
+ size_t Pos=Params.find_first_of('>');
+ if (Pos==string::npos)
+ {
+ // Just echo it
+ cout << RemoveQuotes(Params) << endl;
+ }
+ else
+ {
+ FILE *pfFile;
+ /* Extra the filename */
+ string Filename;
+ if (Params[Pos+1]=='>')
+ {
+ NextItem(Params.substr(Pos+2).c_str(),Filename);
+ fileinfo* pFile=GetFileInfo(Filename,m_MakeDir);
+ // Open file in append
+ pfFile=fopen(pFile->GetFullFileName().c_str(),"a");
+ }
+ else
+ {
+ NextItem(Params.substr(Pos+1).c_str(),Filename);
+ fileinfo* pFile=GetFileInfo(Filename,m_MakeDir);
+ pfFile=fopen(pFile->GetFullFileName().c_str(),"w");
+ }
+ if (!pfFile)
+ {
+ cerr << "Error opening file "<<Filename<<endl;
+ return (mh_pid_t)-1;
+ }
+ string EchoStr=RemoveQuotes(Params.substr(0,Pos))+"\n";
+ if (EchoStr.length()!=fwrite(EchoStr.c_str(),1,EchoStr.length(),pfFile))
+ {
+ cerr << "Error writing file "<<Filename<<endl;
+ return (mh_pid_t)-1;
+ }
+ fclose(pfFile);
+ }
+ return (mh_pid_t)0;
+}
+
+/*****************************************************************************/
+mh_pid_t mhmakefileparser::CopyFiles(const string &Params) const
+{
+ vector<fileinfo*> Files;
+
+ SplitToItems(Params,Files);
+
+ size_t NrSrcs=Files.size()-1;
+
+ if (NrSrcs<1)
+ {
+ cerr << "Wrong number of arguments in copy: "<<Params<<endl;
+ return (mh_pid_t)-1;
+ }
+
+ fileinfo* pDest=Files[NrSrcs];
+ if (NrSrcs>1 && !pDest->IsDir())
+ {
+ cerr << "copy: Destination must be a directory when more then one source : "<<Params<<endl;
+ return (mh_pid_t)-1;
+ }
+
+ for (size_t i=0; i<NrSrcs; i++)
+ {
+ fileinfo* pSrc=Files[i];
+
+ string SrcFileName=pSrc->GetFullFileName();
+
+ if (pSrc->IsDir())
+ {
+ SrcFileName+=OSPATHSEPSTR"*";
+ pSrc=GetFileInfo(SrcFileName,m_MakeDir);
+ }
+
+ //cerr << "copy "<<pSrc->GetFullFileName()<<" "<<pDest->GetFullFileName()<<endl;
+ /* Now check if there is a wildcard */
+ if (SrcFileName.find('*')!=string::npos)
+ {
+ if (!CopyDir(pSrc->GetDir(), pDest, pSrc->GetName()))
+ {
+ cerr << "copy: Error copying directory: " << Params << endl;
+ return (mh_pid_t)-1;
+ }
+ }
+ else
+ {
+ if (!CopyFile(pSrc,pDest))
+ {
+ cerr << "copy: Error copying file: " << Params << endl;
+ return (mh_pid_t)-1;
+ }
+ }
+ }
+
+ return (mh_pid_t)0;
+
+}
+
+/*****************************************************************************/
+mh_pid_t mhmakefileparser::TouchFiles(const string &Params) const
+{
+ vector<fileinfo*> Files;
+
+ SplitToItems(Params,Files);
+
+ vector<fileinfo*>::const_iterator It=Files.begin();
+ while (It!=Files.end())
+ {
+ fileinfo* pFile=*It++;
+ const string &FileName=pFile->GetFullFileName();
+
+ /* Since this can be part of a list of commands for a certain rule, and it is possible that the file
+ * was generated by one on the previous commands, we first need the invalidate the date so that the
+ * existance checking is done again */
+ pFile->InvalidateDate();
+
+ if (pFile->IsDir())
+ {
+ cerr << "touch: Cannot touch a directory: " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ if (pFile->Exists())
+ {
+ int fd;
+ char c;
+ int status = 0;
+ struct stat st;
+ int Ret;
+ int saved_errno = 0;
+
+ fd = open (FileName.c_str(), O_RDWR);
+ if (fd<0)
+ {
+ st.st_size=0;
+ }
+ else
+ {
+ if (fstat (fd, &st) < 0)
+ {
+ cerr << "touch: Cannot stat file " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ }
+
+ if (st.st_size == 0)
+ {
+ FILE *pFile;
+ if (fd>=0 && close(fd) < 0)
+ {
+ cerr << "touch: Error closing file " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ /*Re-Create an empty file */
+ pFile=fopen(FileName.c_str(),"wb");
+ if (!pFile)
+ {
+ cerr << "touch: Cannot create file: " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ fclose(pFile);
+ }
+ else
+ {
+ Ret=read (fd, &c, sizeof(c));
+ if (Ret!=sizeof(c) && Ret!=EOF)
+ {
+ cerr << "touch: Cannot read file " << FileName << ": "<<Ret<<endl;
+ return (mh_pid_t)-1;
+ }
+ if (lseek (fd, (off_t) 0, SEEK_SET) < 0)
+ {
+ cerr << "touch: Error changing file pointer " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ if (write (fd, &c, sizeof c) != sizeof(c))
+ {
+ cerr << "touch: Error writing file " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ if (close (fd) < 0)
+ {
+ cerr << "touch: Error closing file " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ }
+ }
+ else
+ {
+ /* Create an empty file */
+ FILE *pFile=fopen(FileName.c_str(),"wb");
+ if (!pFile)
+ {
+ cerr << "touch: Cannot create file: " << FileName << endl;
+ return (mh_pid_t)-1;
+ }
+ fclose(pFile);
+ }
+ pFile->InvalidateDate();
+ }
+ return (mh_pid_t)0;
+}
+
+/*****************************************************************************/
+const string &mhmakefileparser::GetPythonExe() const
+{
+ static string PythonExe;
+ if (PythonExe.empty())
+ {
+ string FullCommand=SearchCommand(PYTHONEXE);
+ if (!FullCommand.empty())
+ {
+ PythonExe=QuoteFileName(FullCommand)+" ";
+ }
+ else
+ {
+ cerr<<"python executable not found in path and registry.\n";
+ exit(1);
+ }
+ }
+ return PythonExe;
+}
+
+/*****************************************************************************/
+static const string &GetComspec()
+{
+ static string Comspec;
+ if (Comspec.empty())
+ {
+ const char *pComspec=getenv(COMSPEC);
+ if (pComspec)
+ {
+ Comspec=pComspec;
+ #ifdef WIN32
+ Comspec+=" /c ";
+ #else
+ Comspec+=" -c \"";
+ #endif
+ }
+ else
+ {
+ #ifdef WIN32
+ Comspec="cmd.exe /c ";
+ #else
+ Comspec="sh -c \"";
+ #endif
+ }
+ }
+ return Comspec;
+}
+
+/*****************************************************************************/
+static string GetExecutableFromCommand(const string &FullCommand)
+{
+ string Ret;
+ FILE *pFile=fopen(FullCommand.c_str(),"r");
+ if (!pFile)
+ return Ret;
+ char Line[MAX_PATH];
+ if (fgets(Line,MAX_PATH,pFile) && Line[0]=='#' && Line[1]=='!')
+ {
+ Ret=Line+2;
+ Ret.resize(Ret.length()-1);
+ Ret=QuoteFileName(Ret)+" ";
+ }
+ fclose(pFile);
+ return Ret;
+}
+
+/*****************************************************************************/
+string mhmakefileparser::GetFullCommand(const string &CommandIn)
+{
+ map<string,string>::iterator pFound=m_CommandCache.find(CommandIn);
+ string Command=CommandIn;
+ if (pFound==m_CommandCache.end())
+ {
+ bool Found=false;
+ // Not found in the stack, search in the environment path
+ // Check if an extension is specified
+ const char *pBeg=Command.c_str();
+ const char *pEnd=pBeg+Command.length()-1;
+ bool HasExt=false;
+ while (pEnd>pBeg && *pEnd!='\\' && *pEnd!='/')
+ {
+ if (*pEnd=='.')
+ {
+ HasExt=true;
+ break;
+ }
+ pEnd--;
+ }
+ if (HasExt)
+ {
+ string FullCommand=SearchCommand(Command);
+ if (!FullCommand.empty())
+ {
+ Found=true;
+ Command=QuoteFileName(FullCommand);
+ }
+ }
+ else
+ {
+ /* First check for special internal commands */
+ if (CommandIn=="del")
+ {
+ m_CommandCache[CommandIn]="del";
+ return Command;
+ }
+ // Try with different extensions
+ string FullCommand=SearchCommand(Command,EXEEXT);
+ if (!FullCommand.empty())
+ {
+ Found=true;
+ Command=QuoteFileName(FullCommand);
+ }
+ else
+ {
+ FullCommand=SearchCommand(Command,".py");
+ if (!FullCommand.empty())
+ {
+ Found=true;
+ Command=GetPythonExe()+QuoteFileName(FullCommand);
+ }
+ else
+ {
+ // also search without extension, if found look inside the file if we find an executable to use
+ FullCommand=SearchCommand(Command);
+ if (!FullCommand.empty())
+ {
+ Found=true;
+ Command=GetExecutableFromCommand(FullCommand)+QuoteFileName(FullCommand);
+ }
+ }
+ }
+ }
+ if (!Found)
+ {
+ Command=GetComspec()+QuoteFileName(Command);
+ }
+ m_CommandCache[CommandIn]=Command;
+ return Command;
+ }
+ return pFound->second;
+}
+
+static void CommandSep(const string &Command, int &EndPos, int &NextBegin)
+{
+ while (1)
+ {
+ EndPos=Command.find('&',NextBegin);
+ if (EndPos==string::npos || !EndPos)
+ {
+ // When there is only one command return that command, so we run %comspec% commands
+ // always via a temporary batch file. This is to avoid problems when quotes and pipe
+ // characters in parameters when using cmd /c
+ return;
+ }
+ EndPos--;
+ char C=Command[EndPos];
+ NextBegin=EndPos+2;
+ if (strchr("|<>",C))
+ {
+ continue;
+ }
+ if (NextBegin!=Command.length())
+ {
+ C=Command[NextBegin];
+ if (strchr("|<>",C))
+ {
+ continue;
+ }
+ }
+ while (strchr(" \t|<>",Command[NextBegin])) NextBegin++;
+ while (strchr(" \t|<>",Command[EndPos])) EndPos--;
+ break;
+ };
+
+}
+
+mh_pid_t mhmakefileparser::OsExeCommand(const string &Command, const string &Params, bool IgnoreError, string *pOutput) const
+{
+ string FullCommandLine;
+ string ComSpec=GetComspec();
+#ifdef WIN32
+ STARTUPINFO StartupInfo;
+ memset(&StartupInfo,0,sizeof(StartupInfo));
+ StartupInfo.cb=sizeof(STARTUPINFO);
+ PROCESS_INFORMATION ProcessInfo;
+
+ if (Command.substr(0,ComSpec.size())==ComSpec)
+ {
+ string tmpCommand=Command.substr(ComSpec.size(),Command.size());
+ FullCommandLine=ComSpec;
+
+ string ComspecCommandLine=tmpCommand+Params;
+ int NextBegin=0;
+ int EndPos=0;
+ CommandSep(ComspecCommandLine,EndPos,NextBegin);
+ // We have multiple commands so create an temporary batch file
+ FILE *pFile=(FILE*)1;
+ char Filename[MAX_PATH];
+ int Nr=1;
+ while (1)
+ {
+ sprintf(Filename,"%s\\tmp%d.bat",m_MakeDir->GetFullFileName().c_str(),Nr);
+ pFile=fopen(Filename,"r");
+ if (!pFile)
+ break;
+ fclose(pFile);
+ Nr++;
+ }
+ pFile=fopen(Filename,"w");
+ fprintf(pFile,"@echo off\n");
+ int PrevPos=0;
+ while (EndPos!=string::npos)
+ {
+ string SubCommand=ComspecCommandLine.substr(PrevPos,EndPos-PrevPos+1);
+ fprintf(pFile,"%s\n",SubCommand.c_str());
+ PrevPos=NextBegin;
+ CommandSep(ComspecCommandLine,EndPos,NextBegin);
+ }
+ string SubCommand=ComspecCommandLine.substr(PrevPos);
+ fprintf(pFile,"%s\n",SubCommand.c_str());
+ fclose(pFile);
+ FullCommandLine+=QuoteFileName(Filename);
+ ((mhmakefileparser*)this)->m_FilesToRemoveAtEnd.push_back(string(Filename));
+ }
+ else
+ {
+ FullCommandLine=Command+Params;
+ }
+ char *pFullCommand=new char[FullCommandLine.length()+1];
+ strcpy(pFullCommand,FullCommandLine.c_str());
+
+ if (pOutput || g_Quiet)
+ {
+ mh_pid_t hChildStdinRd;
+ mh_pid_t hChildStdinWr;
+ mh_pid_t hChildStdoutRd;
+ mh_pid_t hChildStdoutWr;
+ mh_pid_t hChildStdinWrDup;
+ mh_pid_t hChildStdoutRdDup;
+ SECURITY_ATTRIBUTES saAttr;
+ BOOL fSuccess;
+
+ saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
+ saAttr.bInheritHandle = TRUE;
+ saAttr.lpSecurityDescriptor = NULL;
+
+ if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
+ return (mh_pid_t)-1;
+
+ /* Create new output read handle and the input write handle. Set
+ * the inheritance properties to FALSE. Otherwise, the child inherits
+ * the these handles; resulting in non-closeable handles to the pipes
+ * being created. */
+ fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
+ GetCurrentProcess(), &hChildStdinWrDup, 0,
+ FALSE, DUPLICATE_SAME_ACCESS);
+ if (!fSuccess) return (mh_pid_t)-1;
+ /* Close the inheritable version of ChildStdin that we're using. */
+ CloseHandle(hChildStdinWr);
+
+ if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
+ return (mh_pid_t)-1;
+
+ fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
+ GetCurrentProcess(), &hChildStdoutRdDup, 0,
+ FALSE, DUPLICATE_SAME_ACCESS);
+ if (!fSuccess) return (mh_pid_t)-1;
+ CloseHandle(hChildStdoutRd);
+
+ int hStdIn = _open_osfhandle((long)hChildStdinWrDup, _O_WRONLY|_O_TEXT);
+ FILE *pStdIn = _fdopen(hStdIn, "w");
+ int hStdOut = _open_osfhandle((long)hChildStdoutRdDup, _O_RDONLY|_O_TEXT);
+ FILE *pStdOut = _fdopen(hStdOut, "r");
+
+ StartupInfo.dwFlags = STARTF_USESTDHANDLES;
+ StartupInfo.hStdInput = hChildStdinRd;
+ StartupInfo.hStdOutput = hChildStdoutWr;
+ StartupInfo.hStdError = hChildStdoutWr;
+
+ if (!CreateProcess(NULL,pFullCommand,NULL,NULL,TRUE,CREATE_NO_WINDOW,m_pEnv,m_MakeDir->GetFullFileName().c_str(),&StartupInfo,&ProcessInfo))
+ {
+ delete[] pFullCommand;
+ string ErrorMessage=string("Error starting command: ") + FullCommandLine + " : " + stringify(GetLastError());
+ if (IgnoreError)
+ cerr << ErrorMessage << endl;
+ else
+ throw ErrorMessage;
+ }
+ delete[] pFullCommand;
+ if (!CloseHandle(hChildStdinRd)) return (mh_pid_t)-1;
+ if (!CloseHandle(hChildStdoutWr)) return (mh_pid_t)-1;
+
+ CloseHandle(ProcessInfo.hThread);
+ char Buf[256];
+ size_t Nbr;
+ while ( (Nbr=fread(Buf,1,sizeof(Buf)-1,pStdOut)) > 0)
+ {
+ if (pOutput)
+ {
+ Buf[Nbr]=0;
+ *pOutput+=Buf;
+ }
+ }
+ WaitForSingleObject(ProcessInfo.hProcess,INFINITE);
+ fclose(pStdIn);
+ fclose(pStdOut);
+
+ DWORD ExitCode=0;
+ if (!GetExitCodeProcess(ProcessInfo.hProcess,&ExitCode) || ExitCode)
+ {
+ if (IgnoreError)
+ {
+ cerr << "Error running command: "<<Command<<", but ignoring error\n";
+ return (mh_pid_t)0; // Ignore error
+ }
+ else
+ return (mh_pid_t)-1;
+ }
+ CloseHandle(ProcessInfo.hProcess);
+ return (mh_pid_t)0;
+ }
+ else
+ {
+ if (!CreateProcess(NULL,pFullCommand,NULL,NULL,TRUE,0,m_pEnv,m_MakeDir->GetFullFileName().c_str(),&StartupInfo,&ProcessInfo))
+ {
+ delete[] pFullCommand;
+ string ErrorMessage=string("Error starting command: ") + Command + " : " + stringify(GetLastError());
+ if (IgnoreError)
+ cerr << ErrorMessage << endl;
+ else
+ throw ErrorMessage;
+ }
+ delete[] pFullCommand;
+ CloseHandle(ProcessInfo.hThread);
+ return ProcessInfo.hProcess;
+ }
+#else
+ if (Command.substr(0,ComSpec.size())==ComSpec)
+ {
+ string tmpCommand=Command.substr(ComSpec.size(),Command.size());
+ FullCommandLine=ComSpec;
+ FullCommandLine+=QuoteFileName(tmpCommand)+Params;
+ }
+ else
+ {
+ FullCommandLine=Command+Params;
+ }
+
+ if (pOutput || g_Quiet)
+ {
+ int pipeto[2]; /* pipe to feed the exec'ed program input */
+ int pipefrom[2]; /* pipe to get the exec'ed program output */
+
+ if ( (-1==pipe(pipeto)) || (-1==pipe(pipefrom)) )
+ {
+ if (IgnoreError)
+ {
+ cerr << "Error creating pipe for : "<<Command<<", but ignoring error\n";
+ return (mh_pid_t)0; // Ignore error
+ }
+ else
+ return (mh_pid_t)-1;
+ }
+
+ pid_t ID=vfork();
+ if (ID==-1)
+ {
+ if (IgnoreError)
+ {
+ cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
+ return (mh_pid_t)0; // Ignore error
+ }
+ else
+ return (mh_pid_t)-1;
+ }
+ else if (ID==0)
+ {
+ int argc;
+ const char **pargv;
+
+ dup2( pipeto[0], STDIN_FILENO );
+ dup2( pipefrom[1], STDOUT_FILENO );
+ /* close unnecessary pipe descriptors for a clean environment */
+ close( pipeto[0] );
+ close( pipeto[1] );
+ close( pipefrom[0] );
+ close( pipefrom[1] );
+
+ poptParseArgvString(FullCommandLine.c_str(), &argc, &pargv);
+ if (-1==chdir(m_MakeDir->GetFullFileName().c_str()))
+ throw string("Error changing current directory to ")+m_MakeDir->GetFullFileName();
+ if (m_pEnv)
+ execve(pargv[0],(char *const*)pargv,m_pEnv);
+ else
+ execv(pargv[0],(char *const*)pargv);
+ free(pargv);
+ _exit (EXIT_FAILURE);
+ }
+ else
+ {
+ /* Close unused pipe ends. This is especially important for the
+ * pipefrom[1] write descriptor, otherwise readFromPipe will never
+ * get an EOF. */
+ close( pipeto[0] );
+ close( pipefrom[1] );
+
+ pid_t ID2=vfork();
+ if (ID2==-1)
+ {
+ if (IgnoreError)
+ {
+ cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
+ return (mh_pid_t)0; // Ignore error
+ }
+ else
+ return (mh_pid_t)-1;
+ }
+ else if (ID2==0)
+ {
+ /* Close pipe write descriptor, or we will never know when the
+ * writer process closes its end of the pipe and stops feeding the
+ * exec'ed program. */
+ close( pipeto[1] );
+ char Buf[256];
+ int Nbr;
+ while ( (Nbr=read(pipefrom[0],Buf,sizeof(Buf)-1)) > 0)
+ {
+ if (pOutput)
+ {
+ Buf[Nbr]=0;
+ *pOutput+=Buf;
+ }
+ }
+ close( pipefrom[0]);
+ _exit (EXIT_FAILURE);
+ }
+ else
+ {
+ /* close unused pipe end */
+ close( pipefrom[0] );
+ close( pipeto[1] );
+
+ int Status;
+ waitpid(ID2,&Status,0); // Wait until the reading of the output is finished
+ }
+
+ int Status;
+ int Ret=waitpid(ID,&Status,0);
+ if (Ret!=ID || Status)
+ {
+ if (IgnoreError)
+ {
+ cerr << "Error running command: "<<Command<<", but ignoring error\n";
+ return (mh_pid_t)0; // Ignore error
+ }
+ else
+ return (mh_pid_t)-1;
+ }
+ }
+ }
+ else
+ { // No pOutput
+ pid_t ID=fork();
+ if (ID==-1)
+ {
+ if (IgnoreError)
+ {
+ cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
+ return (mh_pid_t)0; // Ignore error
+ }
+ else
+ return (mh_pid_t)-1;
+ }
+ else if (ID==0)
+ {
+ int argc;
+ const char **pargv;
+
+ poptParseArgvString(FullCommandLine.c_str(), &argc, &pargv);
+ if (-1==chdir(m_MakeDir->GetFullFileName().c_str()))
+ throw string("Error changing current directory to ")+m_MakeDir->GetFullFileName();
+ if (m_pEnv)
+ execve(pargv[0],(char *const*)pargv,m_pEnv);
+ else
+ execv(pargv[0],(char *const*)pargv);
+ free(pargv);
+ _exit (EXIT_FAILURE);
+ }
+ else
+ {
+ return (mh_pid_t)ID;
+ }
+ }
+
+ return (mh_pid_t)0;
+#endif
+}
+
+///////////////////////////////////////////////////////////////////////////////
+#ifndef WIN32
+string EscapeQuotes(const string &Params)
+{
+ int OldPos=0;
+ int Pos;
+ string Quote("\\\"");
+ string SemiColon(" ; ");
+ string Ret;
+
+ while (1)
+ {
+ int Pos=Params.find_first_of('"',OldPos);
+ int Pos2=Params.find(" & ",OldPos);
+ string ToReplace(Quote);
+ int Inc=1;
+
+ if (Pos==string::npos)
+ {
+ if (Pos2==string::npos)
+ break;
+ Pos=Pos2;
+ ToReplace=SemiColon;
+ Inc=3;
+ }
+ else
+ {
+ if (Pos2!=string::npos && Pos2<Pos)
+ {
+ Pos=Pos2;
+ ToReplace=SemiColon;
+ Inc=3;
+ }
+ }
+ Ret+=Params.substr(OldPos,Pos-OldPos);
+ Ret+=ToReplace;
+ OldPos=Pos+Inc;
+ }
+ Ret+=Params.substr(OldPos);
+ return Ret;
+}
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+mh_pid_t mhmakefileparser::ExecuteCommand(string Command, bool &IgnoreError, string *pOutput)
+{
+ bool Echo=true;
+ IgnoreError=false;
+ while (Command.length())
+ {
+ if (Command[0]=='@')
+ {
+ Echo=false;
+ Command=Command.substr(1);
+ continue;
+ }
+ if (Command[0]=='-')
+ {
+ IgnoreError=true;
+ Command=Command.substr(1);
+ continue;
+ }
+ break;
+ }
+ if (!Command.length())
+ (mh_pid_t)0;
+ string InCommand=Command;
+ if (g_Quiet)
+ Echo=false;
+
+ const char *pCom=Command.c_str();
+ int StartCommandPos;
+ int EndCommandPos;
+ int BeginParamPos;
+ if (*pCom=='"')
+ {
+ StartCommandPos=1;
+ EndCommandPos=1;
+ while (pCom[EndCommandPos]!='"') EndCommandPos++;
+ }
+ else
+ {
+ StartCommandPos=0;
+ EndCommandPos=0;
+ }
+ while (!strchr(" \t",pCom[EndCommandPos])) EndCommandPos++;
+ BeginParamPos=EndCommandPos;
+ string Params=Command.substr(BeginParamPos);
+ Command=Command.substr(StartCommandPos,EndCommandPos-StartCommandPos);
+
+ // If we have special characters in the params we always call the command via the shell
+ unsigned i;
+ for (i=0; i<Params.size(); i++)
+ {
+ if (strchr("<>|&",Params[i]))
+ {
+ break;
+ }
+ }
+ if (i==Params.size())
+ {
+ if (Command!="del" && Command!="touch" && Command!="copy" && Command!="echo" && Command!="mkdir")
+ Command=GetFullCommand(Command);
+#ifndef WIN32
+ if (Command.substr(0,GetComspec().size())==GetComspec())
+ {
+ Params=EscapeQuotes(Params);
+ Params+="\"";
+ }
+#endif
+ }
+ else
+ {
+ if (Command!="echo" || strchr(Params.c_str(),'|')) // the EchoCommand(Params) does not implement piping, only redirecting (>)
+ {
+ string FullCommand=GetFullCommand(Command);
+ string ComSpec=GetComspec();
+ if (FullCommand.substr(0,ComSpec.size())!=ComSpec)
+ Command=FullCommand; // Only use FullCommand when it was found and not prepending by the comspec.
+ Command=ComSpec+Command;
+#ifndef WIN32
+ Params=EscapeQuotes(Params);
+ Params+="\"";
+#endif
+ }
+ }
+ if (Echo
+ #ifdef _DEBUG
+ || g_DoNotExecute
+ #endif
+ )
+ {
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << Command << Params << endl;
+ else
+ cout << InCommand << endl;
+ #endif
+ }
+
+ /* first we check special internal commands */
+ #ifdef _DEBUG
+ if (pOutput || !g_DoNotExecute)
+ {
+ #endif
+ if (Command=="del")
+ {
+ return DeleteFiles(Params);
+ }
+ else if (Command=="touch")
+ {
+ return TouchFiles(Params);
+ }
+ else if (Command=="copy")
+ {
+ return CopyFiles(Params);
+ }
+ else if (Command=="echo")
+ {
+ return EchoCommand(Params);
+ }
+ else if (Command=="mkdir")
+ {
+ return MakeDirsCommand(Params);
+ }
+
+ return OsExeCommand(Command,Params,IgnoreError,pOutput);
+ #ifdef _DEBUG
+ }
+ #endif
+ return (mh_pid_t)0; /* No Error */
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::BuildDependencies(const refptr<rule> &pRule, fileinfo* pTarget, mh_time_t TargetDate, mh_time_t &YoungestDate, bool &MakeTarget)
+{
+
+ vector<fileinfo*> &Deps=pTarget->GetDeps();
+ vector<fileinfo*>::iterator pDepIt=Deps.begin();
+ while (pDepIt!=Deps.end())
+ {
+ StartBuildTarget(*pDepIt);
+ pDepIt++;
+ }
+ pDepIt=Deps.begin();
+ while (pDepIt!=Deps.end())
+ {
+ mh_time_t DepDate=WaitBuildTarget(*pDepIt);
+ #ifdef _DEBUG
+ if (!DepDate.DoesExist()&&!(*pDepIt)->IsPhony())
+ {
+ if (!(*pDepIt)->GetDir()->GetDate().DoesExist())
+ cout << "Building of "<<(*pDepIt)->GetFullFileName()<<" failed because directory does not exist (rule defined to create it?)\n";
+ else
+ cout << "Does not known how to create "<<(*pDepIt)->GetFullFileName()<<".\n";
+ }
+ #endif
+ if (DepDate.IsNewer(YoungestDate))
+ YoungestDate=DepDate;
+ if (DepDate.IsNewer(TargetDate))
+ {
+ #ifdef _DEBUG
+ if (pRule&&g_pPrintDependencyCheck && DepDate.IsExistingFile() && TargetDate.IsExistingFile())
+ cout<<"Going to build "<<pTarget->GetQuotedFullFileName()<<" because "<<(*pDepIt)->GetQuotedFullFileName()<<" is more recent\n";
+ #endif
+ MakeTarget=true;
+ }
+ pDepIt++;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+mh_time_t mhmakefileparser::StartBuildTarget(fileinfo* pTarget,bool bCheckTargetDir)
+{
+ #ifdef _DEBUG
+ if (g_CheckCircularDeps)
+ {
+ deque<fileinfo*>::const_iterator pFind=find(m_TargetStack.begin(),m_TargetStack.end(),pTarget);
+ if (pFind!=m_TargetStack.end())
+ {
+ cout << "Circular dependency detected.\n"<<pTarget->GetQuotedFullFileName()<<" depending on itself.\n";
+ cout << "Dependency stack:\n";
+ deque<fileinfo*>::const_iterator pIt=m_TargetStack.begin();
+ while (pIt!=m_TargetStack.end())
+ {
+ cout << " " << (*pIt)->GetQuotedFullFileName() << endl;
+ pIt++;
+ }
+ }
+ if (!pTarget->IsBuildStarted()) m_TargetStack.push_back(pTarget);
+ }
+ #endif
+
+ #ifdef _DEBUG
+ static int Indent;
+ #endif
+
+ if (g_StopCompiling)
+ {
+ throw string("Compilation Interrupted by user.");
+ }
+
+ if (pTarget->IsBuild())
+ {
+ #ifdef _DEBUG
+ if (g_pPrintDependencyCheck)
+ {
+ for (int i=0; i<Indent; i++)
+ cout<<" ";
+ cout<<" Already build "<<pTarget->GetQuotedFullFileName()<<" : "<<pTarget->GetDate()<<endl;
+ }
+ #endif
+ return pTarget->GetDate();
+ }
+ if (pTarget->IsBuilding())
+ return mh_time_t(); // pTarget is still building, so we have to wait
+
+ #ifdef _DEBUG
+ if (g_GenProjectTree)
+ cout << pTarget->GetQuotedFullFileName() << endl;
+
+ Indent++;
+ if (g_pPrintDependencyCheck)
+ {
+ for (int i=0; i<Indent; i++)
+ cout<<" ";
+ cout<<"Building dependencies of "<<pTarget->GetQuotedFullFileName()<<endl;
+ }
+ #endif
+
+ pTarget->SetBuild();
+
+ /* Optimisation: do not build target when target dir does not exist,
+ but first build the target dir, in case there exists a rule for it*/
+ refptr<rule> pRule=pTarget->GetRule();
+
+ if (!pRule && bCheckTargetDir)
+ {
+ fileinfo *pTargetDir=pTarget->GetDir();
+ mh_time_t TargetDirDate=BuildTarget(pTargetDir,false);
+
+ if (!pTargetDir->Exists())
+ {
+ #ifdef _DEBUG
+ Indent--;
+ if (g_CheckCircularDeps)
+ {
+ m_TargetStack.pop_back();
+ }
+ #endif
+ return TargetDirDate;
+ }
+ }
+
+ mh_time_t TargetDate=pTarget->GetDate();
+ mh_time_t YoungestDate=TargetDate;
+ bool MakeTarget=!TargetDate.DoesExist(); // When the target does not exist, always build when a rule is found. This also makes sure the autodepscan will be done in case the target does not exist yet
+
+ if (!pRule || !pRule->GetCommands().size())
+ {
+ implicitruledep_t Result;
+
+ IMPLICITRULE::SearchImplicitRule(pTarget,Result);
+
+ implicitruledep_t::iterator ResultIt=Result.begin();
+ while (ResultIt!=Result.end())
+ {
+ if (ResultIt->first.empty())
+ {
+ pRule=ResultIt->second;
+ pTarget->SetRule(pRule);
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ {
+ cout<<"Found implicit rule for "<<pTarget->GetQuotedFullFileName()<<endl;
+ pRule->PrintCommands(pTarget);
+ }
+ #endif
+ break;
+ }
+ else if (!IMPLICITRULE::PushRule(ResultIt->second))
+ {
+ /* We have to check all the implicitrule dependencies, only when they all can be build,
+ the implicit rule matches */
+ #ifdef _DEBUG
+ fileinfo *pYoungestTarget;
+ m_ImplicitSearch++;
+ #endif
+ mh_time_t ThisYoungestDate=YoungestDate;
+ vector<fileinfo*>::iterator ImplicitRuleDepsIt=ResultIt->first.begin();
+ while (ImplicitRuleDepsIt!=ResultIt->first.end())
+ {
+ fileinfo *pNewTarget=*ImplicitRuleDepsIt;
+ mh_time_t DepDate=BuildTarget(pNewTarget);
+ if (!DepDate.DoesExist())
+ {
+ pNewTarget=ResultIt->second->GetMakefile()->SearchvPath(pNewTarget);
+ if (pNewTarget!=NULL)
+ {
+ *ImplicitRuleDepsIt=pNewTarget; /* The file was elsewere so we have to update the dependencies */
+ DepDate=pNewTarget->GetDate();
+ }
+ }
+ if (!DepDate.DoesExist())
+ break;
+ if (DepDate.IsNewer(ThisYoungestDate))
+ {
+ ThisYoungestDate=DepDate;
+ #ifdef _DEBUG
+ pYoungestTarget=pNewTarget;
+ #endif
+ }
+ ImplicitRuleDepsIt++;
+ }
+
+ IMPLICITRULE::PopRule(ResultIt->second);
+ #ifdef _DEBUG
+ m_ImplicitSearch--;
+ #endif
+ if (ImplicitRuleDepsIt==ResultIt->first.end()) // All deps exists
+ {
+ ThisYoungestDate=YoungestDate;
+ pRule=ResultIt->second;
+ pTarget->InsertDeps(ResultIt->first);
+ pTarget->SetRule(pRule); /* This is an implicit rule so do not add the target */
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ {
+ cout<<"Found implicit rule for "<<pTarget->GetQuotedFullFileName()<<". Dependents:\n";
+ vector<fileinfo*>::iterator ImplicitRuleDepsIt=ResultIt->first.begin();
+ while (ImplicitRuleDepsIt!=ResultIt->first.end())
+ {
+ cout<<" "<<(*ImplicitRuleDepsIt)->GetQuotedFullFileName()<<endl;
+ ImplicitRuleDepsIt++;
+ }
+ pRule->PrintCommands(pTarget);
+ }
+ #endif
+ if (ThisYoungestDate.IsNewer(TargetDate))
+ {
+ #ifdef _DEBUG
+ if (pRule,g_pPrintDependencyCheck && ThisYoungestDate.IsExistingFile() && TargetDate.IsExistingFile())
+ cout<<"Going to build "<<pTarget->GetQuotedFullFileName()<<" because "<<pYoungestTarget->GetQuotedFullFileName()<<" is more recent\n";
+ #endif
+ MakeTarget=true;
+ }
+ break;
+ }
+ }
+ #ifdef _DEBUG
+ else if (g_PrintAdditionalInfo)
+ {
+ cout << "Stopping implicit search of "<<pTarget->GetFullFileName()<<" because of implicit rule recursion detected.\n";
+ }
+ #endif
+ ResultIt++;
+ }
+ if (pRule)
+ {
+ #ifdef _DEBUG
+ pTarget->SetBuilding();
+ pTarget->SetRule(pRule);
+ pTarget->ClearBuilding();
+ #else
+ pTarget->SetRule(pRule);
+ #endif
+ }
+ }
+
+ mhmakefileparser *pMakefile=NULL;
+ if (pRule)
+ {
+ pMakefile=pRule->GetMakefile();
+ if (pMakefile->ForceAutoDepRescan()||MakeTarget==true)
+ pMakefile->UpdateAutomaticDependencies(pTarget);
+ }
+ else if (pTarget->GetAutoDepsMakefile())
+ pTarget->GetAutoDepsMakefile()->UpdateNoRuleAutomaticDependencies(pTarget);
+
+ BuildDependencies(pRule,pTarget,TargetDate,YoungestDate,MakeTarget);
+
+ if (pRule)
+ {
+ #ifdef _DEBUG
+ if (g_pPrintDependencyCheck)
+ {
+ for (int i=0; i<Indent; i++)
+ cout<<" ";
+ cout<<"Building "<<pTarget->GetQuotedFullFileName()<<endl;
+ }
+ #endif
+ if (!MakeTarget)
+ {
+ if (!TargetDate.DoesExist() || ( (g_RebuildAll || pMakefile->m_RebuildAll) && TargetDate.IsOlder(m_sBuildTime)))
+ {
+ #ifdef _DEBUG
+ if (g_pPrintDependencyCheck)
+ {
+ if (!TargetDate.DoesExist())
+ {
+ if (!m_ImplicitSearch && !pTarget->IsPhony())
+ cout<<"Building "<<pTarget->GetQuotedFullFileName()<<" because it does not exist yet\n";
+ }
+ else if (TargetDate.IsOlder(m_sBuildTime))
+ {
+ cout<<"Building "<<pTarget->GetQuotedFullFileName()<<" because need to rebuild all (-a)\n";
+ }
+ }
+ #endif
+ MakeTarget=true;
+ }
+ }
+
+ // Now execute the commands
+ vector<string> &Commands=pRule->GetCommands();
+
+ if (!MakeTarget)
+ {
+ vector<string>::iterator CommandIt=Commands.begin();
+
+ md5_context ctx;
+ md5_starts( &ctx );
+ while (CommandIt!=Commands.end())
+ {
+ pMakefile->SetRuleThatIsBuild(pTarget); // Make sure that the command expension is correct
+ string Command=pMakefile->ExpandExpression(*CommandIt);
+ pMakefile->ClearRuleThatIsBuild(); /* Make sure that further expansion is not taking this rule into account.*/
+ md5_update( &ctx, (uint8 *)Command.c_str(), (unsigned long)Command.size());
+ CommandIt++;
+ }
+
+ uint32 Md5_32=md5_finish32( &ctx);
+ if (!pTarget->CompareMd5_32(Md5_32))
+ {
+ if (TargetDate.IsNewerOrSame(m_sBuildTime) || TargetDate.IsDir())
+ {
+ // Only rebuild if it is not yet rebuild in this current run. This may happen for implicit rules that have multiple targets (implicit rules that build more then one target at the same time
+ pTarget->SetCommandsMd5_32(Md5_32);
+ pMakefile->AddTarget(pTarget);
+ pMakefile->SetAutoDepsDirty(); /* We need to update the autodeps file if the md5 has been changed */
+ }
+ else
+ {
+ #ifdef _DEBUG
+ if (!g_GenProjectTree)
+ cout << "Md5 is different for " << pTarget->GetQuotedFullFileName() << " Old:"<<hex<<pTarget->GetCommandsMd5_32()<<", New: "<<Md5_32<<". Commandline must have been changed so recompiling\n";
+ #endif
+
+ #ifdef _DEBUG
+ Indent--;
+ if (g_CheckCircularDeps)
+ {
+ m_TargetStack.pop_back();
+ }
+ #endif
+
+ MakeTarget=true;
+ }
+ }
+ }
+ if (MakeTarget)
+ {
+ // Queue for execution
+ if (sm_CommandQueue.QueueTarget(pTarget))
+ return mh_time_t();
+ mh_time_t NewDate=pTarget->GetDate();
+ if (NewDate.IsNewer(YoungestDate))
+ YoungestDate=NewDate;
+ }
+ }
+
+ #ifdef _DEBUG
+ if (g_pPrintDependencyCheck)
+ {
+ for (int i=0; i<Indent; i++)
+ cout<<" ";
+ cout<<"Building "<<pTarget->GetQuotedFullFileName()<<" finished : "<< YoungestDate << endl;
+ }
+ Indent--;
+ if (g_CheckCircularDeps)
+ {
+ m_TargetStack.pop_back();
+ }
+
+ if (!m_ImplicitSearch && !pTarget->Exists() && !pTarget->IsPhony() && !g_DoNotExecute && !g_GenProjectTree)
+ {
+ // This is only a warning for phony messages
+ cout<<"Warning: don't know how to make "<<pTarget->GetQuotedFullFileName()<<"\nMake the rule a phony rule to avoid this warning (but only do it when it is really phony).\n";;
+ }
+ #endif
+ pTarget->SetDate(YoungestDate); /* This is especially needed for phony targets in between real targets */
+ return YoungestDate;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+mh_time_t mhmakefileparser::WaitBuildTarget(fileinfo* pTarget)
+{
+ return sm_CommandQueue.WaitForTarget(pTarget);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::BuildIncludedMakefiles()
+{
+ vector<fileinfo*>::iterator MakefileIt=m_IncludedMakefiles.begin();
+ while (MakefileIt!=m_IncludedMakefiles.end())
+ {
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout<<"Building include file "<<(*MakefileIt)->GetQuotedFullFileName()<<endl;
+ #endif
+ BuildTarget(*MakefileIt);
+ MakefileIt++;
+ }
+}
diff --git a/tools/mhmake/src/commandqueue.cpp b/tools/mhmake/src/commandqueue.cpp
new file mode 100644
index 000000000..45a1d1043
--- /dev/null
+++ b/tools/mhmake/src/commandqueue.cpp
@@ -0,0 +1,410 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+
+#include "commandqueue.h"
+#include "mhmakefileparser.h"
+
+#ifndef WIN32
+
+#define INFINITE 0
+#define FALSE 0
+
+static int Status;
+unsigned WaitForMultipleObjects(int Nbr, mh_pid_t *phProcesses, int, int)
+{
+ mh_pid_t ID=waitpid(0,&Status,0);
+ for (int i=0; i<Nbr; i++)
+ {
+ if (ID==phProcesses[i])
+ return i;
+ }
+ return -1;
+}
+
+typedef unsigned DWORD;
+
+int GetExitCodeProcess(mh_pid_t hProcess, DWORD *pExitCode)
+{
+ *pExitCode=Status;
+ return true;
+}
+
+#define CloseHandle(Handle)
+
+#endif
+
+
+commandqueue::commandqueue() :
+ m_NrActiveEntries(0)
+{
+#ifdef WIN32
+ SYSTEM_INFO SysInfo;
+ GetSystemInfo(&SysInfo);
+ m_MaxNrCommandsInParallel=SysInfo.dwNumberOfProcessors;
+
+ m_DummyWaitHandle=(mh_pid_t)CreateEvent(NULL,TRUE,FALSE,NULL);
+#else
+ FILE *pFile=fopen("/proc/cpuinfo","r");
+ const char szProc[]="processor";
+ int cur=0;
+ int NrProcs=0;
+ while (!feof(pFile))
+ {
+ char In=fgetc(pFile);
+ if (In=='\n')
+ {
+ cur=0;
+ }
+ else
+ {
+ if (cur<=sizeof(szProc) && In==szProc[cur])
+ {
+ if (!szProc[cur+1])
+ {
+ NrProcs++;
+ }
+ }
+ cur++;
+ }
+ }
+
+ m_MaxNrCommandsInParallel=NrProcs;
+ m_DummyWaitHandle=(mh_pid_t)-1;
+
+#endif
+
+ m_pActiveProcesses=new mh_pid_t[m_MaxNrCommandsInParallel];
+ m_pActiveEntries= new refptr<activeentry>[m_MaxNrCommandsInParallel];
+}
+
+commandqueue::~commandqueue()
+{
+ delete [] m_pActiveProcesses;
+ delete [] m_pActiveEntries;
+ #ifdef WIN32
+ CloseHandle(m_DummyWaitHandle);
+ #endif
+}
+
+void commandqueue::SetNrParallelBuilds(unsigned NrParallelBuilds)
+{
+ if (m_NrActiveEntries)
+ throw("Changing of number of parallel builds is only allowed when no commands are executing");
+ NrParallelBuilds=max(1u,NrParallelBuilds);
+ m_MaxNrCommandsInParallel=NrParallelBuilds;
+ delete [] m_pActiveProcesses;
+ delete [] m_pActiveEntries;
+ m_pActiveProcesses=new mh_pid_t[NrParallelBuilds];
+ m_pActiveEntries= new refptr<activeentry>[NrParallelBuilds];
+}
+
+void commandqueue::ThrowCommandExecutionError(refptr<activeentry> pActiveEntry)
+{
+ fileinfo* pTarget=pActiveEntry->pTarget;
+ const string &Command=pActiveEntry->Command;
+ mhmakefileparser *pMakefile=pTarget->GetRule()->GetMakefile();
+
+ string ErrorMessage = string("Error running command: ")+ Command +"\n";
+ ErrorMessage += "Command defined in makefile: " + pMakefile->GetMakeDir()->GetQuotedFullFileName();
+ pTarget->SetCommandsMd5_32(0); /* Clear the md5 to make sure that the target is rebuild the next time mhmake is ran */
+ pMakefile->SetAutoDepsDirty(); /* We need to update the autodeps file if the md5 has been changed */
+ throw ErrorMessage;
+}
+
+refptr<commandqueue::activeentry> commandqueue::CreateActiveEntry(void)
+{
+ refptr<activeentry> pRet=new activeentry;
+ m_pActiveEntries[m_NrActiveEntries]=pRet;
+ m_pActiveProcesses[m_NrActiveEntries]=this->m_DummyWaitHandle;
+ m_NrActiveEntries++;
+ return pRet;
+}
+
+unsigned commandqueue::GetActiveEntryId(const refptr<activeentry> pActiveEntry) const
+{
+ unsigned i=0;
+ for (i=0; i<m_NrActiveEntries; i++)
+ if (m_pActiveEntries[i]==pActiveEntry)
+ return i;
+ throw("ActiveEntry not found for "+ pActiveEntry->pTarget->GetFullFileName());
+}
+
+void commandqueue::RemoveActiveEntry(unsigned Entry)
+{
+//cout << "Remove entry "<<Entry<<" of "<<m_NrActiveEntries<<" from queue:"<<m_pActiveEntries[Entry].pTarget->GetQuotedFullFileName()<<<<" ("<<m_pActiveEntries[Entry]<<")\n";
+ unsigned NrToMove=m_NrActiveEntries-Entry-1;
+ if (NrToMove)
+ {
+ for (unsigned i=0; i<NrToMove; i++)
+ {
+ unsigned EntryP1=Entry+1;
+ m_pActiveEntries[Entry]=m_pActiveEntries[EntryP1];
+ m_pActiveProcesses[Entry]=m_pActiveProcesses[EntryP1];
+ Entry=EntryP1;
+ }
+ }
+ m_pActiveEntries[Entry]=NULL;
+ m_pActiveProcesses[Entry]=0;
+ m_NrActiveEntries--;
+}
+
+/* Start to execute next command, return true when command is completely executed
+ upon return */
+bool commandqueue::StartExecuteNextCommand(refptr<activeentry> pActiveEntry, mh_pid_t *pActiveProcess)
+{
+ fileinfo* pTarget=pActiveEntry->pTarget;
+ mhmakefileparser *pMakefile=pTarget->GetRule()->GetMakefile();
+
+ pMakefile->SetRuleThatIsBuild(pTarget); // Make sure that the command expension is correct
+ string Command=pMakefile->ExpandExpression(*pActiveEntry->CurrentCommandIt);
+ pMakefile->ClearRuleThatIsBuild(); /* Make sure that further expansion is not taking this rule into account.*/
+ md5_update( &pActiveEntry->md5ctx, (uint8 *)Command.c_str(), (unsigned long)Command.size());
+
+ pActiveEntry->Command=Command;
+
+ #ifdef _DEBUG
+ if (g_pPrintDependencyCheck)
+ {
+ cout<<"-> "<<Command<<endl;
+ }
+ if (!g_GenProjectTree)
+ {
+ #endif
+ mh_pid_t hProcess=pMakefile->ExecuteCommand(Command,pActiveEntry->IgnoreError);
+ if (hProcess==(mh_pid_t)-1)
+ {
+ ThrowCommandExecutionError(pActiveEntry);
+ }
+ else if (!hProcess)
+ {
+ // Command already finished, so execute next command
+ return true;
+ }
+ else
+ {
+ // Command still executing, so add it to the list of handles to wait for
+ *pActiveProcess=hProcess;
+ return false;
+ }
+ #ifdef _DEBUG
+ }
+ #endif
+ return true;
+}
+
+void commandqueue::TargetBuildFinished(refptr<activeentry> pActiveEntry)
+{
+ fileinfo* pTarget=pActiveEntry->pTarget;
+
+ // Building of this target finished
+ uint32 Md5_32=md5_finish32( &pActiveEntry->md5ctx);
+ #ifdef _DEBUG
+ if (g_DoNotExecute||g_GenProjectTree)
+ pTarget->SetDateToNow();
+ else
+ #endif
+ pTarget->InvalidateDate();
+
+ pTarget->SetCommandsMd5_32(Md5_32); /* If the rule of the target was added with an implicit rule the targets in the rule is empty */
+
+ refptr<rule> pRule=pTarget->GetRule();
+ mhmakefileparser *pMakefile=pRule->GetMakefile();
+
+ pMakefile->AddTarget(pTarget);
+ pMakefile->SetAutoDepsDirty();
+ pRule->SetTargetsIsBuild(Md5_32);
+
+ #ifdef _DEBUG
+ if (g_pPrintDependencyCheck)
+ {
+ cout<<"Building "<<pTarget->GetQuotedFullFileName()<<" finished : "<< pTarget->GetDate() << endl;
+ }
+
+ if (!pMakefile->ImplicitSearch() && !pTarget->Exists() && !pTarget->IsPhony() && !g_DoNotExecute && !g_GenProjectTree)
+ {
+ // This is only a warning for phony messages
+ cout<<"Warning: don't know how to make "<<pTarget->GetQuotedFullFileName()<<"\nMake the rule a phony rule to avoid this warning (but only do it when it is really phony).\n";;
+ }
+ #endif
+
+ pTarget->ClearBuilding();
+}
+
+/* Start executing the commands of a target
+*/
+bool commandqueue::StartExecuteCommands(fileinfo* pTarget)
+{
+ cout << "Building " << pTarget->GetQuotedFullFileName()<<endl;
+ // We do not have to put it in the queue, we can start executing directly
+ refptr<rule> pRule=pTarget->GetRule();
+ mhmakefileparser *pMakefile=pRule->GetMakefile();
+ vector<string>::iterator CommandIt=pRule->GetCommands().begin();
+
+ refptr<activeentry> pActiveEntry=CreateActiveEntry();
+ mh_pid_t ActiveProcess;
+
+ md5_starts( &pActiveEntry->md5ctx );
+
+ pActiveEntry->pTarget=pTarget;
+ pActiveEntry->CurrentCommandIt=CommandIt;
+
+ while (pActiveEntry->CurrentCommandIt!=pRule->GetCommands().end())
+ {
+ if (StartExecuteNextCommand(pActiveEntry, &ActiveProcess))
+ {
+ pActiveEntry->CurrentCommandIt++;
+ }
+ else
+ {
+ m_pActiveProcesses[GetActiveEntryId(pActiveEntry)]=ActiveProcess; // We use GetActiveEntryId to avoid reentrancy problems
+ return false;
+ }
+ }
+ TargetBuildFinished(pActiveEntry);
+ RemoveActiveEntry(pActiveEntry);
+ return true;
+}
+
+
+/* put the target in the execution queue or start executing immediately
+*/
+bool commandqueue::QueueTarget(fileinfo* pTarget)
+{
+ pTarget->SetBuilding();
+ // First check if there is place in the active entries
+ if (m_NrActiveEntries==m_MaxNrCommandsInParallel)
+ {
+ // commands cannot be started yet
+ m_Queue.push(pTarget);
+ return true;
+ }
+ else
+ {
+ return !StartExecuteCommands(pTarget);
+ }
+}
+
+/* Wait for all the commands being executed of a target. In the mean time also continue
+ executing all other commands in the queue
+*/
+mh_time_t commandqueue::WaitForTarget(fileinfo *pTarget)
+{
+ if (!pTarget->IsBuilding())
+ return pTarget->GetDate();
+
+ while (1)
+ {
+ // First wait until one of the processes that are running is finished
+ if (m_NrActiveEntries==1 && m_pActiveProcesses[0]==this->m_DummyWaitHandle)
+ {
+ #ifdef _DEBUG
+ if (pTarget!=m_pActiveEntries[0]->pTarget)
+ throw("Wrong assumption: waiting for target " + pTarget->GetFullFileName() + " but in wait list is " + m_pActiveEntries[0]->pTarget->GetFullFileName());
+ #endif
+ pTarget->SetDateToNow();
+ return pTarget->GetDate(); // This is a reentrancy problem, assume that the target is just build
+ }
+ unsigned Ret=WaitForMultipleObjects(m_NrActiveEntries,m_pActiveProcesses,FALSE,INFINITE);
+ if (Ret>=m_NrActiveEntries)
+ #ifdef WIN32
+ throw("fatal error: unexpected return value of WaitForMultipleObjects " + stringify(Ret) + " " + stringify(GetLastError()));
+ #else
+ throw("fatal error: unexpected return value of WaitForMultipleObjects " + stringify(Ret));
+ #endif
+ refptr<activeentry> pActiveEntry=m_pActiveEntries[Ret];
+ fileinfo* pCurrentTarget=pActiveEntry->pTarget;
+ refptr<rule> pRule=pCurrentTarget->GetRule();
+
+ // First check the error code of the command
+ DWORD ExitCode=0;
+ mh_pid_t hProcess=m_pActiveProcesses[Ret];
+ if (!GetExitCodeProcess(hProcess,&ExitCode) || ExitCode)
+ {
+ if (pActiveEntry->IgnoreError)
+ {
+ cerr << "Error running command: "<<pActiveEntry->Command<<", but ignoring error\n";
+ }
+ else
+ ThrowCommandExecutionError(pActiveEntry);
+ }
+ CloseHandle(hProcess);
+
+ // Now check if we have to execute more commands for this target
+ pActiveEntry->CurrentCommandIt++;
+ while (pActiveEntry->CurrentCommandIt!=pRule->GetCommands().end())
+ {
+ if (!StartExecuteNextCommand(pActiveEntry, &m_pActiveProcesses[Ret]))
+ break; // We have to wait for end of command execution
+ pActiveEntry->CurrentCommandIt++;
+ }
+
+ if (pActiveEntry->CurrentCommandIt==pRule->GetCommands().end())
+ {
+ TargetBuildFinished(pActiveEntry);
+ // Target building finished, so remove it from the list of active entries
+ RemoveActiveEntry(Ret);
+
+ bool Return=false;
+ if (pTarget==pCurrentTarget)
+ {
+ Return = true;
+ }
+ // Check if we have other entries in the queue to start
+ while (1)
+ {
+ if (m_Queue.empty())
+ {
+ // There should still be active entries, otherwise this is a serious bug
+ if (!m_NrActiveEntries && !Return)
+ {
+ // This may happen when having multiple target rules and pTarget was build when on of the other targets
+ // was build. so first check if the pTarget was not build in the mean time. If so, this is not an error
+ if (pTarget->IsBuild())
+ {
+ Return=true;
+ break;
+ }
+ else
+ throw("Fatal error: WaitForTarget "+pTarget->GetQuotedFullFileName()+": no active targets anymore.");
+ }
+ else
+ break;
+ }
+ else
+ {
+ fileinfo* pNewTarget=m_Queue.front();
+ m_Queue.pop();
+ if (StartExecuteCommands(pNewTarget))
+ {
+ if (pNewTarget==pTarget)
+ Return=true;
+ }
+ else
+ break;
+ }
+ }
+ if (Return)
+ return pTarget->GetDate();
+ }
+ }
+
+}
diff --git a/tools/mhmake/src/commandqueue.h b/tools/mhmake/src/commandqueue.h
new file mode 100644
index 000000000..8b327be8c
--- /dev/null
+++ b/tools/mhmake/src/commandqueue.h
@@ -0,0 +1,73 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef __COMMANDQUEUE_H__
+#define __COMMANDQUEUE_H__
+
+#include "fileinfo.h"
+
+#ifdef WIN32
+typedef HANDLE mh_pid_t;
+#else
+typedef pid_t mh_pid_t;
+#endif
+
+class commandqueue
+{
+ struct activeentry : public refbase
+ {
+ fileinfo* pTarget;
+ vector<string>::const_iterator CurrentCommandIt;
+ string Command;
+ md5_context md5ctx;
+ bool IgnoreError;
+ };
+private:
+ queue<fileinfo*> m_Queue;
+ unsigned m_MaxNrCommandsInParallel;
+ mh_pid_t *m_pActiveProcesses;
+ refptr<activeentry> *m_pActiveEntries;
+ unsigned m_NrActiveEntries;
+ mh_pid_t m_DummyWaitHandle;
+
+private:
+ void ThrowCommandExecutionError(refptr<activeentry> pActiveEntry);
+ refptr<activeentry> CreateActiveEntry(void);
+ unsigned GetActiveEntryId(const refptr<activeentry> pActiveEntry) const;
+ void RemoveActiveEntry(unsigned Entry);
+ void RemoveActiveEntry(refptr<activeentry> pActiveEntry)
+ {
+ RemoveActiveEntry(GetActiveEntryId(pActiveEntry));
+ }
+ bool StartExecuteCommands(fileinfo *pTarget);
+ bool StartExecuteNextCommand(refptr<activeentry> pActiveEntry, mh_pid_t *pActiveProcess);
+ void TargetBuildFinished(refptr<activeentry> pActiveEntry);
+
+public:
+ commandqueue();
+ ~commandqueue();
+
+ bool QueueTarget(fileinfo *pTarget); // Returns true if target has been queued, false when commands are executed upon return
+ mh_time_t WaitForTarget(fileinfo *pTarget);
+ void SetNrParallelBuilds(unsigned NrParallelBuilds);
+};
+
+
+#endif
diff --git a/tools/mhmake/src/curdir.cpp b/tools/mhmake/src/curdir.cpp
new file mode 100644
index 000000000..b87dc4f6f
--- /dev/null
+++ b/tools/mhmake/src/curdir.cpp
@@ -0,0 +1,38 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+
+#include "fileinfo.h"
+#include "curdir.h"
+#include "util.h"
+
+fileinfos g_FileInfos; // declare here since it is important that it is constructed before m_pcurrentdir
+curdir::initcurdir curdir::m_pCurrentDir;
+
+///////////////////////////////////////////////////////////////////////////////
+curdir::initcurdir::initcurdir()
+{
+ char CurDir[MAX_PATH];
+ if (!getcwd(CurDir,MAX_PATH))
+ throw string("Error getting current directory.");
+ string strCurDir=CurDir;
+ m_pDir=GetAbsFileInfo(NormalizePathName(strCurDir));
+}
diff --git a/tools/mhmake/src/curdir.h b/tools/mhmake/src/curdir.h
new file mode 100644
index 000000000..138f8f45a
--- /dev/null
+++ b/tools/mhmake/src/curdir.h
@@ -0,0 +1,47 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef __CURDIR_H
+#define __CURDIR_H
+
+class fileinfo;
+
+class curdir
+{
+public:
+ class initcurdir
+ {
+ friend class curdir;
+ const fileinfo *m_pDir;
+ public:
+ initcurdir();
+ };
+private:
+ static initcurdir m_pCurrentDir;
+
+public:
+ static const fileinfo* GetCurDir()
+ {
+ return m_pCurrentDir.m_pDir;
+ }
+};
+
+#endif
+
diff --git a/tools/mhmake/src/fileinfo.cpp b/tools/mhmake/src/fileinfo.cpp
new file mode 100644
index 000000000..939a83ce6
--- /dev/null
+++ b/tools/mhmake/src/fileinfo.cpp
@@ -0,0 +1,369 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+
+#include "fileinfo.h"
+#include "rule.h"
+#include "util.h"
+#include "mhmakefileparser.h"
+
+#ifndef S_ISDIR
+#define S_ISDIR(val) ((val)&_S_IFDIR)
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+string QuoteFileName(const string &Filename)
+{
+ string Ret(Filename);
+#if OSPATHSEP=='\\'
+ /* Put quotes around the string if there are spaces in it */
+ if (Ret.find_first_of(' ')!=string::npos && Ret[0]!='"')
+ {
+ Ret=g_QuoteString+Ret+g_QuoteString;
+ }
+#else
+ int Pos=0;
+ /* Escape the spaces with a backslash */
+ while ((Pos=Ret.find_first_of(' ',Pos))!=string::npos)
+ {
+ Ret=Ret.replace(Pos,1,"\\ ");
+ Pos+=2;
+ }
+#endif
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string UnquoteFileName(const string &Filename)
+{
+ size_t Pos=0;
+ string Name(Filename);
+#if OSPATHSEP=='\\'
+ /* Remove all the quotes from the filename */
+ while ((Pos=Name.find_first_of('"',Pos))!=string::npos)
+ {
+ Name=Name.replace(Pos,1,"");
+ }
+#else
+ /* Remove the escaped spaces */
+ while ((Pos=Name.find_first_of("\\",Pos))!=string::npos)
+ {
+ if (Name[Pos+1]==' ')
+ Name=Name.replace(Pos,2," ");
+ Pos+=1;
+ }
+#endif
+ return Name;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+fileinfo* fileinfo::GetDir() const
+{
+ string Dir=m_AbsFileName.substr(0,m_AbsFileName.find_last_of(OSPATHSEP));
+ #ifdef WIN32
+ if (Dir.length()==2 && Dir[1]==':')
+ #else
+ if (Dir.empty())
+ #endif
+ Dir+=OSPATHSEP;
+ return GetAbsFileInfo(Dir);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string fileinfo::GetName() const
+{
+ return m_AbsFileName.substr(m_AbsFileName.find_last_of(OSPATHSEP)+1);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+mh_time_t fileinfo::realGetDate() const
+{
+ struct stat Buf;
+ if (-1==stat(m_AbsFileName.c_str(),&Buf))
+ ((fileinfo*)this)->m_Date.SetNotExist();
+ else if (S_ISDIR(Buf.st_mode))
+ ((fileinfo*)this)->m_Date.SetDir();
+ else
+ ((fileinfo*)this)->m_Date=Buf.st_mtime;
+ return m_Date;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+bool fileinfo::IsDir() const
+{
+#ifdef WIN32
+ WIN32_FIND_DATA FindData;
+ HANDLE hFind=FindFirstFile(m_AbsFileName.c_str(),&FindData);
+ if (hFind==INVALID_HANDLE_VALUE)
+ {
+ return false;
+ }
+ else
+ {
+ FindClose(hFind);
+ if (FindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+#else
+ struct stat Buf;
+ if (-1==stat(m_AbsFileName.c_str(),&Buf))
+ return false; // File does not exist, so consider this as not a directory
+ else
+ return 0!=S_ISDIR (Buf.st_mode);
+ return true;
+#endif
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void fileinfo::SetDateToNow()
+{
+ m_Date=time(NULL);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string fileinfo::GetPrerequisits() const
+{
+ // Build a string with all prerequisits, but make sure that every dependency
+ // is only in there once (we do this be building a set in parallel
+ vector<fileinfo*>::const_iterator DepIt=m_Deps.begin();
+ deps_t Deps;
+ bool first=true;
+ string Ret=g_EmptyString;
+ while (DepIt!=m_Deps.end())
+ {
+ deps_t::iterator pFound=Deps.find(*DepIt);
+ if (pFound==Deps.end())
+ {
+ if (first)
+ {
+ first=false;
+ }
+ else
+ {
+ Ret+=g_SpaceString;
+ }
+ Ret+=(*DepIt)->GetQuotedFullFileName();
+ }
+ Deps.insert(*DepIt);
+ DepIt++;
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void fileinfo::AddDeps(vector<fileinfo*> &Deps)
+{
+ vector<fileinfo*>::iterator It=Deps.begin();
+ vector<fileinfo*>::iterator ItEnd=Deps.end();
+ while (It!=ItEnd)
+ {
+ AddDep(*It++);
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+bool fileinfo::IsAutoDepExtention(void) const
+{
+ const char *pName=GetFullFileName().c_str();
+ const char *pExt=strrchr(pName,'.');
+ if (!pExt)
+ return false;
+ pExt++;
+ if (m_pRule)
+ {
+ string ObjExt=m_pRule->GetMakefile()->ExpandVar(OBJEXTVAR);
+ return ((0==strcmp(pExt,ObjExt.c_str()+1)) || (0==strcmp(pExt,"h")));
+ }
+ else
+ return ((0==strcmp(pExt,"obj")) || (0==strcmp(pExt,"doj")) || (0==strcmp(pExt,"o")) || (0==strcmp(pExt,"h")));
+}
+
+#ifdef _DEBUG
+///////////////////////////////////////////////////////////////////////////////
+string fileinfo::GetErrorMessageDuplicateRule(const refptr<rule>&pRule)
+{
+ string Ret;
+ Ret = GetQuotedFullFileName() + ": rule is defined multiple times\n";
+ Ret += "First (" + m_pRule->GetMakefile()->GetMakeDir()->GetQuotedFullFileName() + ") :\n";
+
+ vector<string>::const_iterator It=m_pRule->GetCommands().begin();
+ while (It!=m_pRule->GetCommands().end())
+ {
+ Ret+= " " + m_pRule->GetMakefile()->ExpandExpression(*It) + "\n";
+ It++;
+ }
+ Ret += "Second (" + pRule->GetMakefile()->GetMakeDir()->GetQuotedFullFileName() + ") :\n";
+ It=pRule->GetCommands().begin();
+ while (It!=pRule->GetCommands().end())
+ {
+ Ret += " " + pRule->GetMakefile()->ExpandExpression(*It) +"\n";
+ It++;
+ }
+ return Ret;
+}
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+string &NormalizePathName(string &Name)
+{
+ const char *pPtr=Name.c_str();
+ const char *pBeg=pPtr;
+ const char *pLastSlash=NULL;
+ char *pWr=(char*)pBeg;
+ char Char=*pPtr++;
+
+ while (Char)
+ {
+ if (Char=='\\' || Char=='/')
+ {
+ char Char2=pPtr[0];
+ if (Char2=='.')
+ {
+ if (pPtr[1]=='.')
+ {
+ pPtr+=2;
+ while ((pPtr[0]=='\\' || pPtr[0]=='/') && pPtr[1]=='.' && pPtr[2]=='.')
+ {
+ pLastSlash--;
+ while (pLastSlash>pBeg && *pLastSlash!='\\' && *pLastSlash!='/') pLastSlash--; // Be dure to not go further then the beginning of the file name
+ pPtr+=3;
+ }
+ if (pLastSlash)
+ {
+ if (pLastSlash<pBeg)
+ pWr=(char*)pBeg;
+ else
+ pWr=(char*)pLastSlash;
+ }
+ }
+ else
+ {
+ if (pPtr[1]=='\\' || pPtr[1]=='/')
+ {
+ pPtr++;
+ }
+ else
+ {
+ pLastSlash=pWr;
+ *pWr++ = OSPATHSEP;
+ }
+ }
+ }
+ else if (Char2=='\\' || Char2=='/')
+ {
+ }
+ else
+ {
+ pLastSlash=pWr;
+ *pWr++ = OSPATHSEP;
+ }
+ }
+ else
+ {
+ *pWr++ = Char;
+ }
+ Char=*pPtr++;
+ }
+ *pWr=0;
+ Name.resize(pWr-pBeg);
+
+ return Name;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+fileinfo* GetFileInfo(const string &NameIn,const fileinfo* pRelDir)
+{
+ string Name=UnquoteFileName(NameIn);
+ bool DoesExist=true;
+
+ //Only concatenate if szName is not already a full name
+#ifdef WIN32
+ if (!Name.empty() && (Name.length()==1 || Name[1]!=':'))
+#endif
+ {
+ if (Name[0]!=OSPATHSEP)
+ {
+ Name=pRelDir->GetFullFileName()+OSPATHSEPSTR+Name;
+ if (!pRelDir->Exists()) /* if the directory does not exist, the file will not exist either */
+ DoesExist=false;
+ }
+ #ifdef WIN32
+ else
+ {
+ /* The filename is absolute but does not contain a driver letter. So add it (only on windows) */
+ Name=pRelDir->GetFullFileName().substr(0,2)+Name;
+ }
+ #endif
+ }
+ fileinfo* pRet=GetAbsFileInfo(NormalizePathName(Name));
+ if (!DoesExist)
+ pRet->SetNotExist();
+ return pRet;
+}
+
+#ifdef _DEBUG
+///////////////////////////////////////////////////////////////////////////////
+void PrintFileInfos()
+{
+ fileinfos::iterator pIt=g_FileInfos.begin();
+ while (pIt!=g_FileInfos.end())
+ {
+ cout<<(*pIt)->GetQuotedFullFileName()<<" :";
+ if ((*pIt)->IsPhony())
+ cout<<" (phony)";
+ vector<fileinfo*> &Deps=(*pIt)->GetDeps();
+ vector<fileinfo*>::iterator pDepIt=Deps.begin();
+ while (pDepIt!=Deps.end())
+ {
+ cout<<g_SpaceString<<(*pDepIt)->GetQuotedFullFileName();
+ pDepIt++;
+ }
+ cout<<endl;
+ // Write the commands
+ refptr<rule> pRule=(*pIt)->GetRule();
+ if (pRule)
+ {
+ cout<<g_SpaceString<<"Run in: "<<pRule->GetMakefile()->GetMakeDir()->GetQuotedFullFileName()<<endl;
+ pRule->PrintCommands();
+ }
+ pIt++;
+ }
+
+}
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+fileinfos::~fileinfos()
+{
+ fileinfos::iterator It=begin();
+ while (It!=end())
+ {
+ delete (*It);
+ It++;
+ }
+}
diff --git a/tools/mhmake/src/fileinfo.h b/tools/mhmake/src/fileinfo.h
new file mode 100644
index 000000000..b658ac677
--- /dev/null
+++ b/tools/mhmake/src/fileinfo.h
@@ -0,0 +1,442 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef __FILEINFO_H
+#define __FILEINFO_H
+
+#include "curdir.h"
+#include "rule.h"
+#include "md5.h"
+
+#ifdef WIN32
+#define OSPATHSEP '\\'
+#define OSPATHSEPSTR "\\"
+#define OSPATHENVSEP ';'
+#define OSPATHENVSEPSTR ";"
+#else
+#define OSPATHSEP '/'
+#define OSPATHSEPSTR "/"
+#define OSPATHENVSEP ':'
+#define OSPATHENVSEPSTR ":"
+#endif
+
+extern bool g_DumpOnError;
+extern bool g_PrintVarsAndRules;
+extern bool g_DoNotExecute;
+extern bool g_GenProjectTree;
+extern bool g_Quiet;
+extern bool g_RebuildAll;
+extern bool g_PrintAdditionalInfo;
+extern bool g_pPrintDependencyCheck;
+extern bool g_CheckCircularDeps;
+extern bool g_ForceAutoDepRescan;
+extern bool g_PrintLexYacc;
+extern bool g_Clean;
+extern bool g_StopCompiling;
+extern bool g_PrintMultipleDefinedRules;
+
+extern const string g_EmptyString;
+extern const string g_SpaceString;
+extern const string g_QuoteString;
+
+string QuoteFileName(const string &Filename);
+string UnquoteFileName(const string &Filename);
+
+template<typename T>
+inline string stringify(const T& x)
+{
+ ostringstream o;
+ o << x;
+ return o.str();
+}
+
+#define TIMESAFETY 3
+class mh_time
+{
+ enum
+ {
+ DATENOTVALID=0,
+ NOTEXISTTIME=1,
+ DIRTIME =2+TIMESAFETY
+ };
+ unsigned long m_Time;
+
+ bool operator < (const mh_time &Src);
+public:
+ mh_time(){m_Time=DATENOTVALID;}
+ mh_time(time_t Time) : m_Time((unsigned long)Time) {}
+ mh_time(unsigned long Time) : m_Time(Time) {}
+ mh_time(const mh_time &Time) : m_Time(Time.m_Time) {}
+
+ void SetDir(void)
+ {
+ m_Time=DIRTIME;
+ }
+ bool IsDir(void) const
+ {
+ return m_Time==DIRTIME;
+ }
+ void SetNotExist(void)
+ {
+ m_Time=NOTEXISTTIME;
+ }
+ bool IsExistingFile(void) const
+ {
+ return m_Time>DIRTIME;
+ }
+ bool DoesExist(void) const
+ {
+ return m_Time!=NOTEXISTTIME;
+ }
+ void Invalidate(void)
+ {
+ m_Time=DATENOTVALID;
+ }
+ bool IsDateValid(void) const
+ {
+ return m_Time!=DATENOTVALID;
+ }
+ friend ostream& operator<<(ostream& out,const mh_time &Src);
+
+ mh_time &operator = (const mh_time &Src) { m_Time=Src.m_Time; return *this;}
+
+ bool IsOlder(const mh_time &Src) const { return m_Time<Src.m_Time-TIMESAFETY; }
+
+ bool IsNewer(const mh_time &Src) const { return m_Time>Src.m_Time+TIMESAFETY; }
+ bool IsNewerOrSame(const mh_time &Src) const { return m_Time>=Src.m_Time-TIMESAFETY; }
+};
+typedef mh_time mh_time_t;
+
+inline ostream& operator<<(ostream& out,const mh_time &Src)
+{
+ out << hex << (unsigned long)Src.m_Time;
+ return out;
+}
+
+class fileinfo
+{
+ string m_AbsFileName;
+ bool m_IsPhony;
+ int m_BuildStatus; /* Bit 0 means the target built is started, Bit 1 means the target is still building */
+ refptr<rule> m_pRule;
+ mhmakefileparser *m_pAutoDepsMakefile;
+ vector<fileinfo*> m_Deps;
+ mh_time_t m_Date;
+ uint32 m_CommandsMd5_32; // 32-bit Md5 checksum of commands to build this target
+
+ fileinfo(const fileinfo &Src);
+ fileinfo(void);
+
+ void init(const string &AbsFileName,uint32 Md5_32)
+ {
+ m_IsPhony=false;
+ m_pAutoDepsMakefile=NULL;
+ m_BuildStatus=0;
+ m_AbsFileName=UnquoteFileName(AbsFileName);
+ InvalidateDate();
+ m_CommandsMd5_32=Md5_32;
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "Initialising Md5 of "<<GetQuotedFullFileName().c_str()<<" to 0x"<<hex<<Md5_32<<endl;
+ #endif
+ }
+ fileinfo &operator = (const fileinfo &Src); // Do not allow copying
+public:
+ fileinfo(const string &AbsFileName,uint32 Md5_32)
+ {
+ init(AbsFileName,Md5_32);
+ }
+ fileinfo(const string &AbsFileName)
+ {
+ init(AbsFileName,0);
+ }
+ /* The following constructor is only used for name comparisons, and should only be used for that */
+ fileinfo(int Dummy,const string &AbsFileName)
+ {
+ m_AbsFileName=UnquoteFileName(AbsFileName);
+ }
+
+ fileinfo(const char *szFile)
+ {
+ init(szFile,0);
+ }
+ fileinfo(const char *szFile,uint32 Md5_32)
+ {
+ init(szFile,Md5_32);
+ }
+ const string &GetFullFileName(void) const
+ {
+ return m_AbsFileName;
+ }
+ string GetQuotedFullFileName(void) const
+ {
+ return QuoteFileName(m_AbsFileName);
+ }
+#ifdef WIN32
+#define MINPATHLENGTH 3 // The smallest dir name in windows is 3, e.g. "c:\"
+#else
+#define MINPATHLENGTH 1 // The smallest dir name in linux is 1, e.g. "/"
+#endif
+ void SetFullFileName(const string &strAbsName)
+ {
+ m_AbsFileName=UnquoteFileName(strAbsName);
+ // If the last char is path sep strip it, except for the smallest dir name
+ if (m_AbsFileName.length()>MINPATHLENGTH && m_AbsFileName[m_AbsFileName.length()-1]==OSPATHSEP)
+ m_AbsFileName.resize(m_AbsFileName.length()-1);
+ }
+
+ fileinfo* GetDir(void) const;
+ string GetName() const;
+ bool IsDir() const;
+
+ string GetErrorMessageDuplicateRule(const refptr<rule> &pRule);
+
+ void SetRule(refptr<rule> &pRule)
+ {
+ #if defined(_DEBUG) && defined(_MSC_VER)
+ if (m_pRule && m_pRule->GetCommands().size() && !IsBuilding()) {
+ DebugBreak();
+ }
+ #endif
+ m_pRule=pRule;
+ }
+
+ void SetRuleIfNotExist(refptr<rule> &pRule)
+ {
+ if (pRule)
+ {
+ if (!m_pRule)
+ {
+ SetRule(pRule);
+ pRule->AddTarget(this);
+ }
+ #ifdef _DEBUG
+ else
+ {
+ if (*m_pRule!=*pRule)
+ {
+ throw(GetErrorMessageDuplicateRule(pRule));
+ }
+ else if (g_PrintMultipleDefinedRules)
+ {
+ cerr<<GetErrorMessageDuplicateRule(pRule);
+ }
+ }
+ #endif
+ }
+ }
+
+ refptr<rule> GetRule(void) const
+ {
+ return m_pRule;
+ }
+ void AddDep(fileinfo *pDep)
+ {
+ if (&*pDep==this)
+ {
+ #ifdef _DEBUG
+ cout << GetQuotedFullFileName()<<" is directly dependent on itself\n";
+ #endif
+ return;
+ }
+ m_Deps.push_back(pDep);
+ }
+ void AddDeps(vector<fileinfo*> &Deps);
+
+ void InsertDeps(vector<fileinfo*> &Deps)
+ {
+ #ifdef _DEBUG
+ vector<fileinfo*> NewDeps;
+ vector<fileinfo*>::const_iterator It=Deps.begin();
+ vector<fileinfo*>::const_iterator ItEnd=Deps.end();
+ while (It!=ItEnd)
+ {
+ if (&**It==this)
+ {
+ #ifdef _DEBUG
+ cout << GetQuotedFullFileName()<<" is directly dependent on itself\n";
+ #endif
+ }
+ else
+ NewDeps.push_back(*It);
+ It++;
+ }
+ if (NewDeps.size())
+ m_Deps.insert(m_Deps.begin(),NewDeps.begin(),NewDeps.end());
+ #else
+ m_Deps.insert(m_Deps.begin(),Deps.begin(),Deps.end());
+ #endif
+ }
+ vector<fileinfo*> &GetDeps(void)
+ {
+ return m_Deps;
+ }
+ string GetPrerequisits(void) const;
+ void SetAutoDepsScan(mhmakefileparser *pMakefile)
+ {
+ #ifdef _DEBUG
+ if (m_pAutoDepsMakefile)
+ throw(string(".AUTODEPS can only defined ones for rule ")+GetFullFileName());
+ #endif
+ m_pAutoDepsMakefile=pMakefile;
+ }
+ mhmakefileparser *GetAutoDepsMakefile(void) const
+ {
+ return m_pAutoDepsMakefile;
+ }
+ void SetPhony(void)
+ {
+ m_IsPhony=true;
+ m_Date.SetNotExist(); // This will sure that this target will always be build (even if a corresponding file exists)
+ }
+ bool IsPhony(void) const
+ {
+ return m_IsPhony;
+ }
+ mh_time_t realGetDate(void) const;
+ void SetDateToNow(void);
+
+ void SetDate(mh_time_t Date)
+ {
+ m_Date=Date;
+ }
+
+ bool IsDateValid() const
+ {
+ return m_Date.IsDateValid();
+ }
+ void InvalidateDate(void)
+ {
+ m_Date.Invalidate();
+ }
+
+ mh_time_t GetDate(void) const
+ {
+ if (m_Date.IsDateValid())
+ return m_Date;
+ else
+ return realGetDate();
+ }
+ void SetNotExist(void)
+ { // this is used to make sure that this item is rebuild, even if it really exists
+ m_Date.SetNotExist();
+ }
+ bool Exists(void) const
+ {
+ return GetDate().DoesExist();
+ }
+ bool IsBuildStarted(void) const
+ {
+ return (m_BuildStatus&1)==1;
+ }
+ bool IsBuild(void) const
+ {
+ return m_BuildStatus==1;
+ }
+ void SetBuild(void)
+ {
+ m_BuildStatus=1;
+ }
+ bool IsBuilding(void) const
+ {
+ return (m_BuildStatus&2)==2;
+ }
+ void SetBuilding(bool Others=true)
+ {
+ m_BuildStatus|=2;
+ /* Check if there are targets build by the rule attached to this target, if so set them also to building */
+ if (Others && m_pRule)
+ {
+ m_pRule->SetTargetsIsBuilding(this);
+ }
+ }
+ void ClearBuilding(void)
+ {
+ m_BuildStatus&=~2;
+ }
+ bool IsAutoDepExtention(void) const;
+
+ void SetCommandsMd5_32(uint32 Md5_32)
+ {
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "Setting Md5 of "<<GetQuotedFullFileName()<<" to 0x"<<hex<<Md5_32<<endl;
+ #endif
+ m_CommandsMd5_32=Md5_32;
+ }
+#ifdef _DEBUG
+ uint32 GetCommandsMd5_32(void) const
+ {
+ return m_CommandsMd5_32;
+ }
+#endif
+ bool CompareMd5_32(uint32 Md5_32) const
+ {
+ return m_CommandsMd5_32==Md5_32;
+ }
+ void WriteMd5_32(FILE *pFile) const
+ {
+ fwrite(&m_CommandsMd5_32,sizeof(m_CommandsMd5_32),1,pFile);
+ }
+};
+
+struct less_fileinfo : public binary_function <const fileinfo*, const fileinfo*, bool>
+{
+ bool operator()(const fileinfo *_Left, const fileinfo *_Right) const
+ {
+ return less<string>().operator ()(_Left->GetFullFileName(),_Right->GetFullFileName());
+ }
+};
+
+fileinfo *GetFileInfo(const string &szName,const fileinfo* pRelDir);
+
+class fileinfos : public set<fileinfo*,less_fileinfo>
+{
+ public:
+ ~fileinfos();
+};
+
+extern fileinfos g_FileInfos;
+
+inline fileinfo *GetAbsFileInfo(const string &strAbsName)
+{
+ static fileinfo SearchFileInfo("");
+ SearchFileInfo.SetFullFileName(strAbsName);
+ /* Using find is just an optimalisation, you could use insert immediately */
+ fileinfos::const_iterator pFind=g_FileInfos.find(&SearchFileInfo);
+ if (pFind==g_FileInfos.end())
+ {
+ pair <fileinfos::iterator, bool> pPair=g_FileInfos.insert(new fileinfo(SearchFileInfo.GetFullFileName()));
+ return *(pPair.first);
+ }
+ else
+ return *pFind;
+}
+
+inline fileinfo *GetFileInfo(const char *szName,const fileinfo* pRelDir)
+{
+ return GetFileInfo(string(szName),pRelDir);
+}
+
+string &NormalizePathName(string &Name);
+void PrintFileInfos();
+
+#endif
+
diff --git a/tools/mhmake/src/flex.skl b/tools/mhmake/src/flex.skl
new file mode 100644
index 000000000..6db7e1c5c
--- /dev/null
+++ b/tools/mhmake/src/flex.skl
@@ -0,0 +1,3425 @@
+%# -*-C-*- vi: set ft=c:
+%# This file is processed in several stages.
+%# Here are the stages, as best as I can describe:
+%#
+%# 1. flex.skl is processed through GNU m4 during the
+%# pre-compilation stage of flex. Only macros starting
+%# with `m4preproc_' are processed, and quoting is normal.
+%#
+%# 2. The preprocessed skeleton is translated verbatim into a
+%# C array, saved as "skel.c" and compiled into the flex binary.
+%#
+%# 3. At runtime, the skeleton is generated and filtered (again)
+%# through m4. Macros beginning with `m4_' will be processed.
+%# The quoting is "[[" and "]]" so we don't interfere with
+%# user code.
+%#
+%# All generate macros for the m4 stage contain the text "m4" or "M4"
+%# in them. This is to distinguish them from CPP macros.
+%# The exception to this rule is YY_G, which is an m4 macro,
+%# but it needs to be remain short because it is used everywhere.
+%#
+/* A lexical scanner generated by flex */
+
+%# Macros for preproc stage.
+
+%# Macros for runtime processing stage.
+m4_changecom
+m4_changequote
+m4_changequote([[, ]])
+
+%#
+%# Lines in this skeleton starting with a "%" character are "control lines"
+%# and affect the generation of the scanner. The possible control codes are
+%# listed and processed in misc.c.
+%#
+%# %# - A comment. The current line is omitted from the generated scanner.
+%# %if-c++-only - The following lines are printed for C++ scanners ONLY.
+%# %if-c-only - The following lines are NOT printed for C++ scanners.
+%# %if-c-or-c++ - The following lines are printed in BOTH C and C++ scanners.
+%# %if-reentrant - Print for reentrant scanners.(push)
+%# %if-not-reentrant - Print for non-reentrant scanners. (push)
+%# %if-bison-bridge - Print for bison-bridge. (push)
+%# %if-not-bison-bridge - Print for non-bison-bridge. (push)
+%# %endif - pop from the previous if code.
+%# %% - A stop-point, where code is inserted by flex.
+%# Each stop-point is numbered here and also in the code generator.
+%# (See gen.c, etc. for details.)
+%# %not-for-header - Begin code that should NOT appear in a ".h" file.
+%# %ok-for-header - %c and %e are used for building a header file.
+%# %if-tables-serialization
+%#
+%# All control-lines EXCEPT comment lines ("%#") will be inserted into
+%# the generated scanner as a C-style comment. This is to aid those who
+%# edit the skeleton.
+%#
+
+%not-for-header
+%if-c-only
+%if-not-reentrant
+m4_ifelse(M4_YY_PREFIX,yy,,
+#define yy_create_buffer M4_YY_PREFIX[[_create_buffer]]
+#define yy_delete_buffer M4_YY_PREFIX[[_delete_buffer]]
+#define yy_flex_debug M4_YY_PREFIX[[_flex_debug]]
+#define yy_init_buffer M4_YY_PREFIX[[_init_buffer]]
+#define yy_flush_buffer M4_YY_PREFIX[[_flush_buffer]]
+#define yy_load_buffer_state M4_YY_PREFIX[[_load_buffer_state]]
+#define yy_switch_to_buffer M4_YY_PREFIX[[_switch_to_buffer]]
+#define yyin M4_YY_PREFIX[[in]]
+#define yyleng M4_YY_PREFIX[[leng]]
+#define yylex M4_YY_PREFIX[[lex]]
+#define yylineno M4_YY_PREFIX[[lineno]]
+#define yyout M4_YY_PREFIX[[out]]
+#define yyrestart M4_YY_PREFIX[[restart]]
+#define yytext M4_YY_PREFIX[[text]]
+#define yywrap M4_YY_PREFIX[[wrap]]
+#define yyalloc M4_YY_PREFIX[[alloc]]
+#define yyrealloc M4_YY_PREFIX[[realloc]]
+#define yyfree M4_YY_PREFIX[[free]]
+)
+%endif
+%endif
+%ok-for-header
+
+#define FLEX_SCANNER
+#define YY_FLEX_MAJOR_VERSION FLEX_MAJOR_VERSION
+#define YY_FLEX_MINOR_VERSION FLEX_MINOR_VERSION
+#define YY_FLEX_SUBMINOR_VERSION FLEX_SUBMINOR_VERSION
+#if YY_FLEX_SUBMINOR_VERSION > 0
+#define FLEX_BETA
+#endif
+
+%# Some negated symbols
+m4_ifdef( [[M4_YY_IN_HEADER]], , [[m4_define([[M4_YY_NOT_IN_HEADER]], [[]])]])
+m4_ifdef( [[M4_YY_REENTRANT]], , [[m4_define([[M4_YY_NOT_REENTRANT]], [[]])]])
+
+%# This is the m4 way to say "(stack_used || is_reentrant)
+m4_ifdef( [[M4_YY_STACK_USED]], [[m4_define([[M4_YY_HAS_START_STACK_VARS]])]])
+m4_ifdef( [[M4_YY_REENTRANT]], [[m4_define([[M4_YY_HAS_START_STACK_VARS]])]])
+
+%# Prefixes.
+%# The complexity here is necessary so that m4 preserves
+%# the argument lists to each C function.
+
+
+m4_ifdef( [[M4_YY_PREFIX]],, [[m4_define([[M4_YY_PREFIX]], [[yy]])]])
+
+%if-c++-only
+ /* The c++ scanner is a mess. The FlexLexer.h header file relies on the
+ * following macro. This is required in order to pass the c++-multiple-scanners
+ * test in the regression suite. We get reports that it breaks inheritance.
+ * We will address this in a future release of flex, or omit the C++ scanner
+ * altogether.
+ */
+ #define yyFlexLexer M4_YY_PREFIX[[FlexLexer]]
+%endif
+
+%if-c-only
+ M4_GEN_PREFIX(`_create_buffer')
+ M4_GEN_PREFIX(`_delete_buffer')
+ M4_GEN_PREFIX(`_scan_buffer')
+ M4_GEN_PREFIX(`_scan_string')
+ M4_GEN_PREFIX(`_scan_bytes')
+ M4_GEN_PREFIX(`_init_buffer')
+ M4_GEN_PREFIX(`_flush_buffer')
+ M4_GEN_PREFIX(`_load_buffer_state')
+ M4_GEN_PREFIX(`_switch_to_buffer')
+ M4_GEN_PREFIX(`push_buffer_state')
+ M4_GEN_PREFIX(`pop_buffer_state')
+ M4_GEN_PREFIX(`ensure_buffer_stack')
+ M4_GEN_PREFIX(`lex')
+ M4_GEN_PREFIX(`restart')
+ M4_GEN_PREFIX(`lex_init')
+ M4_GEN_PREFIX(`lex_init_extra')
+ M4_GEN_PREFIX(`lex_destroy')
+ M4_GEN_PREFIX(`get_debug')
+ M4_GEN_PREFIX(`set_debug')
+ M4_GEN_PREFIX(`get_extra')
+ M4_GEN_PREFIX(`set_extra')
+ M4_GEN_PREFIX(`get_in')
+ M4_GEN_PREFIX(`set_in')
+ M4_GEN_PREFIX(`get_out')
+ M4_GEN_PREFIX(`set_out')
+ M4_GEN_PREFIX(`get_leng')
+ M4_GEN_PREFIX(`get_text')
+ M4_GEN_PREFIX(`get_lineno')
+ M4_GEN_PREFIX(`set_lineno')
+ m4_ifdef( [[M4_YY_REENTRANT]],
+ [[
+ M4_GEN_PREFIX(`get_column')
+ M4_GEN_PREFIX(`set_column')
+ ]])
+ M4_GEN_PREFIX(`wrap')
+%endif
+
+m4_ifdef( [[M4_YY_BISON_LVAL]],
+[[
+ M4_GEN_PREFIX(`get_lval')
+ M4_GEN_PREFIX(`set_lval')
+]])
+
+m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+[[
+ M4_GEN_PREFIX(`get_lloc')
+ M4_GEN_PREFIX(`set_lloc')
+]])
+
+%if-c-only
+m4_ifdef( [[M4_YY_NOT_REENTRANT]],
+[[
+ M4_GEN_PREFIX(`text')
+ M4_GEN_PREFIX(`leng')
+ M4_GEN_PREFIX(`in')
+ M4_GEN_PREFIX(`out')
+ M4_GEN_PREFIX(`_flex_debug')
+ M4_GEN_PREFIX(`lineno')
+]])
+%endif
+
+
+m4_ifdef( [[M4_YY_TABLES_EXTERNAL]],
+[[
+ M4_GEN_PREFIX(`tables_fload')
+ M4_GEN_PREFIX(`tables_destroy')
+ M4_GEN_PREFIX(`TABLES_NAME')
+]])
+
+/* First, we deal with platform-specific or compiler-specific issues. */
+
+/* begin standard C headers. */
+%if-c-only
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <stdlib.h>
+%endif
+
+%if-tables-serialization
+#include <sys/types.h>
+#include <netinet/in.h>
+%endif
+/* end standard C headers. */
+
+%if-c-or-c++
+#include <flexint.h>
+%endif
+
+%if-c++-only
+/* begin standard C++ headers. */
+#include <iostream>
+#include <errno.h>
+#include <cstdlib>
+#include <cstring>
+/* end standard C++ headers. */
+%endif
+
+#ifdef __cplusplus
+
+/* The "const" storage-class-modifier is valid. */
+#define YY_USE_CONST
+
+#else /* ! __cplusplus */
+
+/* C99 requires __STDC__ to be defined as 1. */
+#if defined (__STDC__)
+
+#define YY_USE_CONST
+
+#endif /* defined (__STDC__) */
+#endif /* ! __cplusplus */
+
+#ifdef YY_USE_CONST
+#define yyconst const
+#else
+#define yyconst
+#endif
+
+%# For compilers that can not handle prototypes.
+%# e.g.,
+%# The function prototype
+%# int foo(int x, char* y);
+%#
+%# ...should be written as
+%# int foo M4_YY_PARAMS(int x, char* y);
+%#
+%# ...which could possibly generate
+%# int foo ();
+%#
+m4_ifdef( [[M4_YY_NO_ANSI_FUNC_PROTOS]],
+[[
+ m4_define( [[M4_YY_PARAMS]], [[()]])
+]],
+[[
+ m4_define( [[M4_YY_PARAMS]], [[($*)]])
+]])
+
+%not-for-header
+/* Returned upon end-of-file. */
+#define YY_NULL 0
+%ok-for-header
+
+%not-for-header
+/* Promotes a possibly negative, possibly signed char to an unsigned
+ * integer for use as an array index. If the signed char is negative,
+ * we want to instead treat it as an 8-bit unsigned char, hence the
+ * double cast.
+ */
+#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+%ok-for-header
+
+
+
+%if-reentrant
+
+/* An opaque pointer. */
+#ifndef YY_TYPEDEF_YY_SCANNER_T
+#define YY_TYPEDEF_YY_SCANNER_T
+typedef void* yyscan_t;
+#endif
+
+%# Declare yyguts variable
+m4_define( [[M4_YY_DECL_GUTS_VAR]], [[struct yyguts_t * yyg = (struct yyguts_t*)yyscanner]])
+%# For use wherever a Global is accessed or assigned.
+m4_define( [[YY_G]], [[yyg->$1]])
+
+%# For use in function prototypes to append the additional argument.
+m4_define( [[M4_YY_PROTO_LAST_ARG]], [[, yyscan_t yyscanner]])
+m4_define( [[M4_YY_PROTO_ONLY_ARG]], [[yyscan_t yyscanner]])
+
+%# For use in function definitions to append the additional argument.
+m4_ifdef( [[M4_YY_NO_ANSI_FUNC_DEFS]],
+[[
+ m4_define( [[M4_YY_DEF_LAST_ARG]], [[, yyscanner]])
+ m4_define( [[M4_YY_DEF_ONLY_ARG]], [[yyscanner]])
+]],
+[[
+ m4_define( [[M4_YY_DEF_LAST_ARG]], [[, yyscan_t yyscanner]])
+ m4_define( [[M4_YY_DEF_ONLY_ARG]], [[yyscan_t yyscanner]])
+]])
+m4_define( [[M4_YY_DECL_LAST_ARG]], [[yyscan_t yyscanner;]])
+
+%# For use in function calls to pass the additional argument.
+m4_define( [[M4_YY_CALL_LAST_ARG]], [[, yyscanner]])
+m4_define( [[M4_YY_CALL_ONLY_ARG]], [[yyscanner]])
+
+%# For use in function documentation to adjust for additional argument.
+m4_define( [[M4_YY_DOC_PARAM]], [[@param yyscanner The scanner object.]])
+
+/* For convenience, these vars (plus the bison vars far below)
+ are macros in the reentrant scanner. */
+#define yyin YY_G(yyin_r)
+#define yyout YY_G(yyout_r)
+#define yyextra YY_G(yyextra_r)
+#define yyleng YY_G(yyleng_r)
+#define yytext YY_G(yytext_r)
+#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno)
+#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
+#define yy_flex_debug YY_G(yy_flex_debug_r)
+
+m4_define( [[M4_YY_INCR_LINENO]],
+[[
+ do{ yylineno++;
+ yycolumn=0;
+ }while(0)
+]])
+
+%endif
+
+
+
+%if-not-reentrant
+
+m4_define( [[M4_YY_INCR_LINENO]],
+[[
+ yylineno++;
+]])
+
+%# Define these macros to be no-ops.
+m4_define( [[M4_YY_DECL_GUTS_VAR]], [[m4_dnl]])
+m4_define( [[YY_G]], [[($1)]])
+m4_define( [[M4_YY_PROTO_LAST_ARG]])
+m4_define( [[M4_YY_PROTO_ONLY_ARG]], [[void]])
+m4_define( [[M4_YY_DEF_LAST_ARG]])
+
+m4_ifdef( [[M4_YY_NO_ANSI_FUNC_DEFS]],
+[[
+ m4_define( [[M4_YY_DEF_ONLY_ARG]])
+]],
+[[
+ m4_define( [[M4_YY_DEF_ONLY_ARG]], [[void]])
+]])
+m4_define([[M4_YY_DECL_LAST_ARG]])
+m4_define([[M4_YY_CALL_LAST_ARG]])
+m4_define([[M4_YY_CALL_ONLY_ARG]])
+m4_define( [[M4_YY_DOC_PARAM]], [[]])
+
+%endif
+
+
+m4_ifdef( [[M4_YY_NO_ANSI_FUNC_DEFS]],
+[[
+%# For compilers that need traditional function definitions.
+%# e.g.,
+%# The function prototype taking 2 arguments
+%# int foo (int x, char* y)
+%#
+%# ...should be written as
+%# int foo YYFARGS2(int,x, char*,y)
+%#
+%# ...which could possibly generate
+%# int foo (x,y,yyscanner)
+%# int x;
+%# char * y;
+%# yyscan_t yyscanner;
+%#
+%# Generate traditional function defs
+ m4_define( [[YYFARGS0]], [[(M4_YY_DEF_ONLY_ARG) [[\]]
+ M4_YY_DECL_LAST_ARG]])
+ m4_define( [[YYFARGS1]], [[($2 M4_YY_DEF_LAST_ARG) [[\]]
+ $1 $2; [[\]]
+ M4_YY_DECL_LAST_ARG]])
+ m4_define( [[YYFARGS2]], [[($2,$4 M4_YY_DEF_LAST_ARG) [[\]]
+ $1 $2; [[\]]
+ $3 $4; [[\]]
+ M4_YY_DECL_LAST_ARG]])
+ m4_define( [[YYFARGS3]], [[($2,$4,$6 M4_YY_DEF_LAST_ARG) [[\]]
+ $1 $2; [[\]]
+ $3 $4; [[\]]
+ $5 $6; [[\]]
+ M4_YY_DECL_LAST_ARG]])
+]],
+[[
+%# Generate C99 function defs.
+ m4_define( [[YYFARGS0]], [[(M4_YY_DEF_ONLY_ARG)]])
+ m4_define( [[YYFARGS1]], [[($1 $2 M4_YY_DEF_LAST_ARG)]])
+ m4_define( [[YYFARGS2]], [[($1 $2, $3 $4 M4_YY_DEF_LAST_ARG)]])
+ m4_define( [[YYFARGS3]], [[($1 $2, $3 $4, $5 $6 M4_YY_DEF_LAST_ARG)]])
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Enter a start condition. This macro really ought to take a parameter,
+ * but we do it the disgusting crufty way forced on us by the ()-less
+ * definition of BEGIN.
+ */
+#define BEGIN YY_G(yy_start) = 1 + 2 *
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Translate the current start state into a value that can be later handed
+ * to BEGIN to return to the state. The YYSTATE alias is for lex
+ * compatibility.
+ */
+#define YY_START ((YY_G(yy_start) - 1) / 2)
+#define YYSTATE YY_START
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Action number for EOF rule of a given start state. */
+#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Special action meaning "start processing a new file". */
+#define YY_NEW_FILE yyrestart( yyin M4_YY_CALL_LAST_ARG )
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define YY_END_OF_BUFFER_CHAR 0
+]])
+
+/* Size of default input buffer. */
+#ifndef YY_BUF_SIZE
+#define YY_BUF_SIZE 16384
+#endif
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* The state buf must be large enough to hold one state per character in the main buffer.
+ */
+#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
+]])
+
+
+#ifndef YY_TYPEDEF_YY_BUFFER_STATE
+#define YY_TYPEDEF_YY_BUFFER_STATE
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+#endif
+
+%if-not-reentrant
+extern int yyleng;
+%endif
+
+%if-c-only
+%if-not-reentrant
+extern FILE *yyin, *yyout;
+%endif
+%endif
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define EOB_ACT_CONTINUE_SCAN 0
+#define EOB_ACT_END_OF_FILE 1
+#define EOB_ACT_LAST_MATCH 2
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+ m4_ifdef( [[M4_YY_USE_LINENO]],
+ [[
+ /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires
+ * access to the local variable yy_act. Since yyless() is a macro, it would break
+ * existing scanners that call yyless() from OUTSIDE yylex.
+ * One obvious solution it to make yy_act a global. I tried that, and saw
+ * a 5% performance hit in a non-yylineno scanner, because yy_act is
+ * normally declared as a register variable-- so it is not worth it.
+ */
+ #define YY_LESS_LINENO(n) \
+ do { \
+ int yyl;\
+ for ( yyl = n; yyl < yyleng; ++yyl )\
+ if ( yytext[yyl] == '\n' )\
+ --yylineno;\
+ }while(0)
+ ]],
+ [[
+ #define YY_LESS_LINENO(n)
+ ]])
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Return all but the first "n" matched characters back to the input stream. */
+#define yyless(n) \
+ do \
+ { \
+ /* Undo effects of setting up yytext. */ \
+ int yyless_macro_arg = (n); \
+ YY_LESS_LINENO(yyless_macro_arg);\
+ *yy_cp = YY_G(yy_hold_char); \
+ YY_RESTORE_YY_MORE_OFFSET \
+ YY_G(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+ YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+ } \
+ while ( 0 )
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define unput(c) yyunput( c, YY_G(yytext_ptr) M4_YY_CALL_LAST_ARG )
+]])
+
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef size_t yy_size_t;
+#endif
+
+#ifndef YY_STRUCT_YY_BUFFER_STATE
+#define YY_STRUCT_YY_BUFFER_STATE
+struct yy_buffer_state
+ {
+%if-c-only
+ FILE *yy_input_file;
+%endif
+
+%if-c++-only
+ std::istream* yy_input_file;
+%endif
+
+
+ char *yy_ch_buf; /* input buffer */
+ char *yy_buf_pos; /* current position in input buffer */
+
+ /* Size of input buffer in bytes, not including room for EOB
+ * characters.
+ */
+ yy_size_t yy_buf_size;
+
+ /* Number of characters read into yy_ch_buf, not including EOB
+ * characters.
+ */
+ int yy_n_chars;
+
+ /* Whether we "own" the buffer - i.e., we know we created it,
+ * and can realloc() it to grow it, and should free() it to
+ * delete it.
+ */
+ int yy_is_our_buffer;
+
+ /* Whether this is an "interactive" input source; if so, and
+ * if we're using stdio for input, then we want to use getc()
+ * instead of fread(), to make sure we stop fetching input after
+ * each newline.
+ */
+ int yy_is_interactive;
+
+ /* Whether we're considered to be at the beginning of a line.
+ * If so, '^' rules will be active on the next match, otherwise
+ * not.
+ */
+ int yy_at_bol;
+
+ int yy_bs_lineno; /**< The line count. */
+ int yy_bs_column; /**< The column count. */
+
+
+ /* Whether to try to fill the input buffer when we reach the
+ * end of it.
+ */
+ int yy_fill_buffer;
+
+ int yy_buffer_status;
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define YY_BUFFER_NEW 0
+#define YY_BUFFER_NORMAL 1
+ /* When an EOF's been seen but there's still some text to process
+ * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+ * shouldn't try reading from the input source any more. We might
+ * still have a bunch of tokens to match, though, because of
+ * possible backing-up.
+ *
+ * When we actually see the EOF, we change the status to "new"
+ * (via yyrestart()), so that the user can continue scanning by
+ * just pointing yyin at a new input file.
+ */
+#define YY_BUFFER_EOF_PENDING 2
+]])
+ };
+#endif /* !YY_STRUCT_YY_BUFFER_STATE */
+
+%if-c-only Standard (non-C++) definition
+%not-for-header
+%if-not-reentrant
+
+/* Stack of input buffers. */
+static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
+static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
+static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
+%endif
+%ok-for-header
+%endif
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* We provide macros for accessing buffer states in case in the
+ * future we want to put the buffer states in a more general
+ * "scanner state".
+ *
+ * Returns the top of the stack, or NULL.
+ */
+#define YY_CURRENT_BUFFER ( YY_G(yy_buffer_stack) \
+ ? YY_G(yy_buffer_stack)[YY_G(yy_buffer_stack_top)] \
+ : NULL)
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Same as previous macro, but useful when we know that the buffer stack is not
+ * NULL or when we need an lvalue. For internal use only.
+ */
+#define YY_CURRENT_BUFFER_LVALUE YY_G(yy_buffer_stack)[YY_G(yy_buffer_stack_top)]
+]])
+
+%if-c-only Standard (non-C++) definition
+
+%if-not-reentrant
+%not-for-header
+/* yy_hold_char holds the character lost when yytext is formed. */
+static char yy_hold_char;
+static int yy_n_chars; /* number of characters read into yy_ch_buf */
+int yyleng;
+
+/* Points to current character in buffer. */
+static char *yy_c_buf_p = (char *) 0;
+static int yy_init = 0; /* whether we need to initialize */
+static int yy_start = 0; /* start state number */
+
+/* Flag which is used to allow yywrap()'s to do buffer switches
+ * instead of setting up a fresh yyin. A bit of a hack ...
+ */
+static int yy_did_buffer_switch_on_eof;
+%ok-for-header
+%endif
+
+void yyrestart M4_YY_PARAMS( FILE *input_file M4_YY_PROTO_LAST_ARG );
+void yy_switch_to_buffer M4_YY_PARAMS( YY_BUFFER_STATE new_buffer M4_YY_PROTO_LAST_ARG );
+YY_BUFFER_STATE yy_create_buffer M4_YY_PARAMS( FILE *file, int size M4_YY_PROTO_LAST_ARG );
+void yy_delete_buffer M4_YY_PARAMS( YY_BUFFER_STATE b M4_YY_PROTO_LAST_ARG );
+void yy_flush_buffer M4_YY_PARAMS( YY_BUFFER_STATE b M4_YY_PROTO_LAST_ARG );
+void yypush_buffer_state M4_YY_PARAMS( YY_BUFFER_STATE new_buffer M4_YY_PROTO_LAST_ARG );
+void yypop_buffer_state M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+static void yyensure_buffer_stack M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+static void yy_load_buffer_state M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+static void yy_init_buffer M4_YY_PARAMS( YY_BUFFER_STATE b, FILE *file M4_YY_PROTO_LAST_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER M4_YY_CALL_LAST_ARG)
+]])
+
+YY_BUFFER_STATE yy_scan_buffer M4_YY_PARAMS( char *base, yy_size_t size M4_YY_PROTO_LAST_ARG );
+YY_BUFFER_STATE yy_scan_string M4_YY_PARAMS( yyconst char *yy_str M4_YY_PROTO_LAST_ARG );
+YY_BUFFER_STATE yy_scan_bytes M4_YY_PARAMS( yyconst char *bytes, int len M4_YY_PROTO_LAST_ARG );
+
+%endif
+
+void *yyalloc M4_YY_PARAMS( yy_size_t M4_YY_PROTO_LAST_ARG );
+void *yyrealloc M4_YY_PARAMS( void *, yy_size_t M4_YY_PROTO_LAST_ARG );
+void yyfree M4_YY_PARAMS( void * M4_YY_PROTO_LAST_ARG );
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define yy_new_buffer yy_create_buffer
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define yy_set_interactive(is_interactive) \
+ { \
+ if ( ! YY_CURRENT_BUFFER ){ \
+ yyensure_buffer_stack (M4_YY_CALL_ONLY_ARG); \
+ YY_CURRENT_BUFFER_LVALUE = \
+ yy_create_buffer( yyin, YY_BUF_SIZE M4_YY_CALL_LAST_ARG); \
+ } \
+ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+ }
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define yy_set_bol(at_bol) \
+ { \
+ if ( ! YY_CURRENT_BUFFER ){\
+ yyensure_buffer_stack (M4_YY_CALL_ONLY_ARG); \
+ YY_CURRENT_BUFFER_LVALUE = \
+ yy_create_buffer( yyin, YY_BUF_SIZE M4_YY_CALL_LAST_ARG); \
+ } \
+ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+ }
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
+]])
+
+%% [1.0] yytext/yyin/yyout/yy_state_type/yylineno etc. def's & init go here
+
+%if-c-only Standard (non-C++) definition
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+static yy_state_type yy_get_previous_state M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+static yy_state_type yy_try_NUL_trans M4_YY_PARAMS( yy_state_type current_state M4_YY_PROTO_LAST_ARG);
+static int yy_get_next_buffer M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+static void yy_fatal_error M4_YY_PARAMS( yyconst char msg[] M4_YY_PROTO_LAST_ARG );
+]])
+
+%endif
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Done after the current pattern has been matched and before the
+ * corresponding action - sets up yytext.
+ */
+#define YY_DO_BEFORE_ACTION \
+ YY_G(yytext_ptr) = yy_bp; \
+%% [2.0] code to fiddle yytext and yyleng for yymore() goes here \
+ YY_G(yy_hold_char) = *yy_cp; \
+ *yy_cp = '\0'; \
+%% [3.0] code to copy yytext_ptr to yytext[] goes here, if %array \
+ YY_G(yy_c_buf_p) = yy_cp;
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+%% [4.0] data tables for the DFA and the user's section 1 definitions go here
+]])
+
+m4_ifdef( [[M4_YY_IN_HEADER]], [[#ifdef YY_HEADER_EXPORT_START_CONDITIONS]])
+M4_YY_SC_DEFS
+m4_ifdef( [[M4_YY_IN_HEADER]], [[#endif]])
+
+m4_ifdef( [[M4_YY_NO_UNISTD_H]],,
+[[
+#ifndef YY_NO_UNISTD_H
+/* Special case for "unistd.h", since it is non-ANSI. We include it way
+ * down here because we want the user's section 1 to have been scanned first.
+ * The user has a chance to override it with an option.
+ */
+%if-c-only
+#include <unistd.h>
+%endif
+%if-c++-only
+#include <unistd.h>
+%endif
+#endif
+]])
+
+m4_ifdef( [[M4_EXTRA_TYPE_DEFS]],
+[[
+#define YY_EXTRA_TYPE M4_EXTRA_TYPE_DEFS
+]],
+[[
+#ifndef YY_EXTRA_TYPE
+#define YY_EXTRA_TYPE void *
+#endif
+]]
+)
+
+%if-c-only Reentrant structure and macros (non-C++).
+%if-reentrant
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Holds the entire state of the reentrant scanner. */
+struct yyguts_t
+ {
+
+ /* User-defined. Not touched by flex. */
+ YY_EXTRA_TYPE yyextra_r;
+
+ /* The rest are the same as the globals declared in the non-reentrant scanner. */
+ FILE *yyin_r, *yyout_r;
+ size_t yy_buffer_stack_top; /**< index of top of stack. */
+ size_t yy_buffer_stack_max; /**< capacity of stack. */
+ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */
+ char yy_hold_char;
+ int yy_n_chars;
+ int yyleng_r;
+ char *yy_c_buf_p;
+ int yy_init;
+ int yy_start;
+ int yy_did_buffer_switch_on_eof;
+ int yy_start_stack_ptr;
+ int yy_start_stack_depth;
+ int *yy_start_stack;
+ yy_state_type yy_last_accepting_state;
+ char* yy_last_accepting_cpos;
+
+ int yylineno_r;
+ int yy_flex_debug_r;
+
+m4_ifdef( [[M4_YY_USES_REJECT]],
+[[
+ yy_state_type *yy_state_buf;
+ yy_state_type *yy_state_ptr;
+ char *yy_full_match;
+ int yy_lp;
+
+ /* These are only needed for trailing context rules,
+ * but there's no conditional variable for that yet. */
+ int yy_looking_for_trail_begin;
+ int yy_full_lp;
+ int *yy_full_state;
+]])
+
+m4_ifdef( [[M4_YY_TEXT_IS_ARRAY]],
+[[
+ char yytext_r[YYLMAX];
+ char *yytext_ptr;
+ int yy_more_offset;
+ int yy_prev_more_offset;
+]],
+[[
+ char *yytext_r;
+ int yy_more_flag;
+ int yy_more_len;
+]])
+
+m4_ifdef( [[M4_YY_BISON_LVAL]],
+[[
+ YYSTYPE * yylval_r;
+]])
+
+m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+[[
+ YYLTYPE * yylloc_r;
+]])
+
+ }; /* end struct yyguts_t */
+]])
+
+
+%if-c-only
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+static int yy_init_globals M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+%endif
+
+%if-reentrant
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+ m4_ifdef( [[M4_YY_BISON_LVAL]],
+ [[
+ /* This must go here because YYSTYPE and YYLTYPE are included
+ * from bison output in section 1.*/
+ # define yylval YY_G(yylval_r)
+ ]])
+
+ m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+ [[
+ # define yylloc YY_G(yylloc_r)
+ ]])
+]])
+
+int yylex_init M4_YY_PARAMS(yyscan_t* scanner);
+
+int yylex_init_extra M4_YY_PARAMS( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
+
+%endif
+
+%endif End reentrant structures and macros.
+
+/* Accessor methods to globals.
+ These are made visible to non-reentrant scanners for convenience. */
+
+m4_ifdef( [[M4_YY_NO_DESTROY]],,
+[[
+int yylex_destroy M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_DEBUG]],,
+[[
+int yyget_debug M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_DEBUG]],,
+[[
+void yyset_debug M4_YY_PARAMS( int debug_flag M4_YY_PROTO_LAST_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_EXTRA]],,
+[[
+YY_EXTRA_TYPE yyget_extra M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_EXTRA]],,
+[[
+void yyset_extra M4_YY_PARAMS( YY_EXTRA_TYPE user_defined M4_YY_PROTO_LAST_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_IN]],,
+[[
+FILE *yyget_in M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_IN]],,
+[[
+void yyset_in M4_YY_PARAMS( FILE * in_str M4_YY_PROTO_LAST_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_OUT]],,
+[[
+FILE *yyget_out M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_OUT]],,
+[[
+void yyset_out M4_YY_PARAMS( FILE * out_str M4_YY_PROTO_LAST_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_LENG]],,
+[[
+int yyget_leng M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_TEXT]],,
+[[
+char *yyget_text M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_LINENO]],,
+[[
+int yyget_lineno M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_LINENO]],,
+[[
+void yyset_lineno M4_YY_PARAMS( int line_number M4_YY_PROTO_LAST_ARG );
+]])
+
+%if-bison-bridge
+m4_ifdef( [[M4_YY_NO_GET_LVAL]],,
+[[
+YYSTYPE * yyget_lval M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+]])
+
+void yyset_lval M4_YY_PARAMS( YYSTYPE * yylval_param M4_YY_PROTO_LAST_ARG );
+
+m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+[[
+ m4_ifdef( [[M4_YY_NO_GET_LLOC]],,
+ [[
+ YYLTYPE *yyget_lloc M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+ ]])
+
+ m4_ifdef( [[M4_YY_NO_SET_LLOC]],,
+ [[
+ void yyset_lloc M4_YY_PARAMS( YYLTYPE * yylloc_param M4_YY_PROTO_LAST_ARG );
+ ]])
+]])
+%endif
+
+/* Macros after this point can all be overridden by user definitions in
+ * section 1.
+ */
+
+#ifndef YY_SKIP_YYWRAP
+#ifdef __cplusplus
+extern "C" int yywrap M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+#else
+extern int yywrap M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+#endif
+#endif
+
+%not-for-header
+ m4_ifdef( [[M4_YY_NO_UNPUT]],,
+ [[
+ static void yyunput M4_YY_PARAMS( int c, char *buf_ptr M4_YY_PROTO_LAST_ARG);
+ ]])
+%ok-for-header
+%endif
+
+#ifndef yytext_ptr
+static void yy_flex_strncpy M4_YY_PARAMS( char *, yyconst char *, int M4_YY_PROTO_LAST_ARG);
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen M4_YY_PARAMS( yyconst char * M4_YY_PROTO_LAST_ARG);
+#endif
+
+#ifndef YY_NO_INPUT
+%if-c-only Standard (non-C++) definition
+%not-for-header
+#ifdef __cplusplus
+static int yyinput M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+#else
+static int input M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+#endif
+%ok-for-header
+%endif
+#endif
+
+
+%if-c-only
+%# TODO: This is messy.
+m4_ifdef( [[M4_YY_STACK_USED]],
+[[
+
+m4_ifdef( [[M4_YY_NOT_REENTRANT]],
+[[
+ m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+ [[
+ static int yy_start_stack_ptr = 0;
+ static int yy_start_stack_depth = 0;
+ static int *yy_start_stack = NULL;
+ ]])
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+ m4_ifdef( [[M4_YY_NO_PUSH_STATE]],,
+ [[
+ static void yy_push_state M4_YY_PARAMS( int new_state M4_YY_PROTO_LAST_ARG);
+ ]])
+ m4_ifdef( [[M4_YY_NO_POP_STATE]],,
+ [[
+ static void yy_pop_state M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+ ]])
+ m4_ifdef( [[M4_YY_NO_TOP_STATE]],,
+ [[
+ static int yy_top_state M4_YY_PARAMS( M4_YY_PROTO_ONLY_ARG );
+ ]])
+]])
+
+]],
+[[
+m4_define( [[M4_YY_NO_PUSH_STATE]])
+m4_define( [[M4_YY_NO_POP_STATE]])
+m4_define( [[M4_YY_NO_TOP_STATE]])
+]])
+%endif
+
+/* Amount of stuff to slurp up with each read. */
+#ifndef YY_READ_BUF_SIZE
+#define YY_READ_BUF_SIZE 8192
+#endif
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Copy whatever the last rule matched to the standard output. */
+#ifndef ECHO
+%if-c-only Standard (non-C++) definition
+/* This used to be an fputs(), but since the string might contain NUL's,
+ * we now use fwrite().
+ */
+#define ECHO fwrite( yytext, yyleng, 1, yyout )
+%endif
+%if-c++-only C++ definition
+#define ECHO LexerOutput( yytext, yyleng )
+%endif
+#endif
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
+ * is returned in "result".
+ */
+#ifndef YY_INPUT
+#define YY_INPUT(buf,result,max_size) \
+%% [5.0] fread()/read() definition of YY_INPUT goes here unless we're doing C++ \
+\
+%if-c++-only C++ definition \
+ if ( (result = LexerInput( (char *) buf, max_size )) < 0 ) \
+ YY_FATAL_ERROR( "input in flex scanner failed" );
+%endif
+
+#endif
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* No semi-colon after return; correct usage is to write "yyterminate();" -
+ * we don't want an extra ';' after the "return" because that will cause
+ * some compilers to complain about unreachable statements.
+ */
+#ifndef yyterminate
+#define yyterminate() return YY_NULL
+#endif
+]])
+
+/* Number of entries by which start-condition stack grows. */
+#ifndef YY_START_STACK_INCR
+#define YY_START_STACK_INCR 25
+#endif
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Report a fatal error. */
+#ifndef YY_FATAL_ERROR
+%if-c-only
+#define YY_FATAL_ERROR(msg) yy_fatal_error( msg M4_YY_CALL_LAST_ARG)
+%endif
+%if-c++-only
+#define YY_FATAL_ERROR(msg) LexerError( msg )
+%endif
+#endif
+]])
+
+%if-tables-serialization structures and prototypes
+m4preproc_include(`tables_shared.h')
+
+/* Load the DFA tables from the given stream. */
+int yytables_fload M4_YY_PARAMS(FILE * fp M4_YY_PROTO_LAST_ARG);
+
+/* Unload the tables from memory. */
+int yytables_destroy M4_YY_PARAMS(M4_YY_PROTO_ONLY_ARG);
+%not-for-header
+
+/** Describes a mapping from a serialized table id to its deserialized state in
+ * this scanner. This is the bridge between our "generic" deserialization code
+ * and the specifics of this scanner.
+ */
+struct yytbl_dmap {
+ enum yytbl_id dm_id;/**< table identifier */
+ void **dm_arr; /**< address of pointer to store the deserialized table. */
+ size_t dm_sz; /**< local sizeof() each element in table. */
+};
+
+/** A {0,0,0}-terminated list of structs, forming the map */
+static struct yytbl_dmap yydmap[] =
+{
+%tables-yydmap generated elements
+ {0,0,0}
+};
+
+/** A tables-reader object to maintain some state in the read. */
+struct yytbl_reader {
+ FILE * fp; /**< input stream */
+ flex_uint32_t bread; /**< bytes read since beginning of current tableset */
+};
+
+%endif
+/* end tables serialization structures and prototypes */
+
+%ok-for-header
+
+/* Default declaration of generated scanner - a define so the user can
+ * easily add parameters.
+ */
+#ifndef YY_DECL
+#define YY_DECL_IS_OURS 1
+%if-c-only Standard (non-C++) definition
+
+
+m4_define( [[M4_YY_LEX_PROTO]], [[M4_YY_PARAMS(M4_YY_PROTO_ONLY_ARG)]])
+m4_define( [[M4_YY_LEX_DECLARATION]], [[YYFARGS0(void)]])
+
+m4_ifdef( [[M4_YY_BISON_LVAL]],
+[[
+ m4_dnl The bison pure parser is used. Redefine yylex to
+ m4_dnl accept the lval parameter.
+
+ m4_define( [[M4_YY_LEX_PROTO]], [[\]]
+ [[M4_YY_PARAMS(YYSTYPE * yylval_param M4_YY_PROTO_LAST_ARG)]])
+ m4_define( [[M4_YY_LEX_DECLARATION]], [[\]]
+ [[YYFARGS1(YYSTYPE *,yylval_param)]])
+]])
+
+m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+[[
+ m4_dnl Locations are used. yylex should also accept the ylloc parameter.
+
+ m4_define( [[M4_YY_LEX_PROTO]], [[\]]
+ [[M4_YY_PARAMS(YYSTYPE * yylval_param, YYLTYPE * yylloc_param M4_YY_PROTO_LAST_ARG)]])
+ m4_define( [[M4_YY_LEX_DECLARATION]], [[\]]
+ [[YYFARGS2(YYSTYPE *,yylval_param, YYLTYPE *,yylloc_param)]])
+]])
+
+extern int yylex M4_YY_LEX_PROTO;
+
+#define YY_DECL int yylex M4_YY_LEX_DECLARATION
+%endif
+%if-c++-only C++ definition
+#define YY_DECL int yyFlexLexer::yylex()
+%endif
+#endif /* !YY_DECL */
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Code executed at the beginning of each rule, after yytext and yyleng
+ * have been set up.
+ */
+#ifndef YY_USER_ACTION
+#define YY_USER_ACTION
+#endif
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* Code executed at the end of each rule. */
+#ifndef YY_BREAK
+#define YY_BREAK break;
+#endif
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+%% [6.0] YY_RULE_SETUP definition goes here
+]])
+
+%not-for-header
+/** The main scanner function which does all the work.
+ */
+YY_DECL
+{
+ register yy_state_type yy_current_state;
+ register char *yy_cp, *yy_bp;
+ register int yy_act;
+ M4_YY_DECL_GUTS_VAR();
+
+m4_ifdef( [[M4_YY_NOT_REENTRANT]],
+[[
+ m4_ifdef( [[M4_YY_BISON_LVAL]],
+ [[
+ YYSTYPE * yylval;
+ ]])
+ m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+ [[
+ YYLTYPE * yylloc;
+ ]])
+]])
+
+%% [7.0] user's declarations go here
+
+m4_ifdef( [[M4_YY_BISON_LVAL]],
+[[
+ yylval = yylval_param;
+]])
+
+m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+[[
+ yylloc = yylloc_param;
+]])
+
+ if ( !YY_G(yy_init) )
+ {
+ YY_G(yy_init) = 1;
+
+#ifdef YY_USER_INIT
+ YY_USER_INIT;
+#endif
+
+m4_ifdef( [[M4_YY_USES_REJECT]],
+[[
+ /* Create the reject buffer large enough to save one state per allowed character. */
+ if ( ! YY_G(yy_state_buf) )
+ YY_G(yy_state_buf) = (yy_state_type *)yyalloc(YY_STATE_BUF_SIZE M4_YY_CALL_LAST_ARG);
+ if ( ! YY_G(yy_state_buf) )
+ YY_FATAL_ERROR( "out of dynamic memory in yylex()" );
+]])
+
+ if ( ! YY_G(yy_start) )
+ YY_G(yy_start) = 1; /* first start state */
+
+ if ( ! yyin )
+%if-c-only
+ yyin = stdin;
+%endif
+%if-c++-only
+ yyin = & std::cin;
+%endif
+
+ if ( ! yyout )
+%if-c-only
+ yyout = stdout;
+%endif
+%if-c++-only
+ yyout = & std::cout;
+%endif
+
+ if ( ! YY_CURRENT_BUFFER ) {
+ yyensure_buffer_stack (M4_YY_CALL_ONLY_ARG);
+ YY_CURRENT_BUFFER_LVALUE =
+ yy_create_buffer( yyin, YY_BUF_SIZE M4_YY_CALL_LAST_ARG);
+ }
+
+ yy_load_buffer_state( M4_YY_CALL_ONLY_ARG );
+ }
+
+ while ( 1 ) /* loops until end-of-file is reached */
+ {
+%% [8.0] yymore()-related code goes here
+ yy_cp = YY_G(yy_c_buf_p);
+
+ /* Support of yytext. */
+ *yy_cp = YY_G(yy_hold_char);
+
+ /* yy_bp points to the position in yy_ch_buf of the start of
+ * the current run.
+ */
+ yy_bp = yy_cp;
+
+%% [9.0] code to set up and find next match goes here
+
+yy_find_action:
+%% [10.0] code to find the action number goes here
+
+ YY_DO_BEFORE_ACTION;
+
+%% [11.0] code for yylineno update goes here
+
+do_action: /* This label is used only to access EOF actions. */
+
+%% [12.0] debug code goes here
+
+ switch ( yy_act )
+ { /* beginning of action switch */
+%% [13.0] actions go here
+
+ case YY_END_OF_BUFFER:
+ {
+ /* Amount of text matched not including the EOB char. */
+ int yy_amount_of_matched_text = (int) (yy_cp - YY_G(yytext_ptr)) - 1;
+
+ /* Undo the effects of YY_DO_BEFORE_ACTION. */
+ *yy_cp = YY_G(yy_hold_char);
+ YY_RESTORE_YY_MORE_OFFSET
+
+ if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+ {
+ /* We're scanning a new file or input source. It's
+ * possible that this happened because the user
+ * just pointed yyin at a new source and called
+ * yylex(). If so, then we have to assure
+ * consistency between YY_CURRENT_BUFFER and our
+ * globals. Here is the right place to do so, because
+ * this is the first action (other than possibly a
+ * back-up) that will match for the new input source.
+ */
+ YY_G(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+ YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+ YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+ }
+
+ /* Note that here we test for yy_c_buf_p "<=" to the position
+ * of the first EOB in the buffer, since yy_c_buf_p will
+ * already have been incremented past the NUL character
+ * (since all states make transitions on EOB to the
+ * end-of-buffer state). Contrast this with the test
+ * in input().
+ */
+ if ( YY_G(yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[YY_G(yy_n_chars)] )
+ { /* This was really a NUL. */
+ yy_state_type yy_next_state;
+
+ YY_G(yy_c_buf_p) = YY_G(yytext_ptr) + yy_amount_of_matched_text;
+
+ yy_current_state = yy_get_previous_state( M4_YY_CALL_ONLY_ARG );
+
+ /* Okay, we're now positioned to make the NUL
+ * transition. We couldn't have
+ * yy_get_previous_state() go ahead and do it
+ * for us because it doesn't know how to deal
+ * with the possibility of jamming (and we don't
+ * want to build jamming into it because then it
+ * will run more slowly).
+ */
+
+ yy_next_state = yy_try_NUL_trans( yy_current_state M4_YY_CALL_LAST_ARG);
+
+ yy_bp = YY_G(yytext_ptr) + YY_MORE_ADJ;
+
+ if ( yy_next_state )
+ {
+ /* Consume the NUL. */
+ yy_cp = ++YY_G(yy_c_buf_p);
+ yy_current_state = yy_next_state;
+ goto yy_match;
+ }
+
+ else
+ {
+%% [14.0] code to do back-up for compressed tables and set up yy_cp goes here
+ goto yy_find_action;
+ }
+ }
+
+ else switch ( yy_get_next_buffer( M4_YY_CALL_ONLY_ARG ) )
+ {
+ case EOB_ACT_END_OF_FILE:
+ {
+ YY_G(yy_did_buffer_switch_on_eof) = 0;
+
+ if ( yywrap( M4_YY_CALL_ONLY_ARG ) )
+ {
+ /* Note: because we've taken care in
+ * yy_get_next_buffer() to have set up
+ * yytext, we can now set up
+ * yy_c_buf_p so that if some total
+ * hoser (like flex itself) wants to
+ * call the scanner after we return the
+ * YY_NULL, it'll still work - another
+ * YY_NULL will get returned.
+ */
+ YY_G(yy_c_buf_p) = YY_G(yytext_ptr) + YY_MORE_ADJ;
+
+ yy_act = YY_STATE_EOF(YY_START);
+ goto do_action;
+ }
+
+ else
+ {
+ if ( ! YY_G(yy_did_buffer_switch_on_eof) )
+ YY_NEW_FILE;
+ }
+ break;
+ }
+
+ case EOB_ACT_CONTINUE_SCAN:
+ YY_G(yy_c_buf_p) =
+ YY_G(yytext_ptr) + yy_amount_of_matched_text;
+
+ yy_current_state = yy_get_previous_state( M4_YY_CALL_ONLY_ARG );
+
+ yy_cp = YY_G(yy_c_buf_p);
+ yy_bp = YY_G(yytext_ptr) + YY_MORE_ADJ;
+ goto yy_match;
+
+ case EOB_ACT_LAST_MATCH:
+ YY_G(yy_c_buf_p) =
+ &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[YY_G(yy_n_chars)];
+
+ yy_current_state = yy_get_previous_state( M4_YY_CALL_ONLY_ARG );
+
+ yy_cp = YY_G(yy_c_buf_p);
+ yy_bp = YY_G(yytext_ptr) + YY_MORE_ADJ;
+ goto yy_find_action;
+ }
+ break;
+ }
+
+ default:
+ YY_FATAL_ERROR(
+ "fatal flex scanner internal error--no action found" );
+ } /* end of action switch */
+ } /* end of scanning one token */
+} /* end of yylex */
+%ok-for-header
+
+%if-c++-only
+%not-for-header
+/* The contents of this function are C++ specific, so the YY_G macro is not used.
+ */
+yyFlexLexer::yyFlexLexer( std::istream* arg_yyin, std::ostream* arg_yyout )
+{
+ yyin = arg_yyin;
+ yyout = arg_yyout;
+ yy_c_buf_p = 0;
+ yy_init = 0;
+ yy_start = 0;
+ yy_flex_debug = 0;
+
+ yy_did_buffer_switch_on_eof = 0;
+
+ yy_looking_for_trail_begin = 0;
+ yy_more_flag = 0;
+ yy_more_len = 0;
+ yy_more_offset = yy_prev_more_offset = 0;
+
+ yy_start_stack_ptr = yy_start_stack_depth = 0;
+ yy_start_stack = NULL;
+
+ yy_buffer_stack = 0;
+ yy_buffer_stack_top = 0;
+ yy_buffer_stack_max = 0;
+
+
+m4_ifdef( [[M4_YY_USES_REJECT]],
+[[
+ yy_state_buf = new yy_state_type[YY_STATE_BUF_SIZE];
+]],
+[[
+ yy_state_buf = 0;
+]])
+}
+
+/* The contents of this function are C++ specific, so the YY_G macro is not used.
+ */
+yyFlexLexer::~yyFlexLexer()
+{
+ mystack::iterator It=m_IncludeStack.begin();
+ while (It!=m_IncludeStack.end())
+ {
+ yy_delete_buffer((*It)->m_BufferState); /* When the stack is deleted, the lexer is not run anymore, so we have to clean up the buffers ourself */
+ It++;
+ }
+ delete [] yy_state_buf;
+ yyfree( yy_start_stack M4_YY_CALL_LAST_ARG );
+ yy_delete_buffer( YY_CURRENT_BUFFER M4_YY_CALL_LAST_ARG);
+ yyfree( yy_buffer_stack M4_YY_CALL_LAST_ARG );
+}
+
+/* The contents of this function are C++ specific, so the YY_G macro is not used.
+ */
+void yyFlexLexer::switch_streams( std::istream* new_in, std::ostream* new_out )
+{
+ if ( new_in )
+ {
+ yy_delete_buffer( YY_CURRENT_BUFFER M4_YY_CALL_LAST_ARG);
+ yy_switch_to_buffer( yy_create_buffer( new_in, YY_BUF_SIZE M4_YY_CALL_LAST_ARG) M4_YY_CALL_LAST_ARG);
+ }
+
+ if ( new_out )
+ yyout = new_out;
+}
+
+#ifdef YY_INTERACTIVE
+int yyFlexLexer::LexerInput( char* buf, int /* max_size */ )
+#else
+int yyFlexLexer::LexerInput( char* buf, int max_size )
+#endif
+{
+ if ( yyin->eof() || yyin->fail() )
+ return 0;
+
+#ifdef YY_INTERACTIVE
+ yyin->get( buf[0] );
+
+ if ( yyin->eof() )
+ return 0;
+
+ if ( yyin->bad() )
+ return -1;
+
+ return 1;
+
+#else
+ (void) yyin->read( buf, max_size );
+
+ if ( yyin->bad() )
+ return -1;
+ else
+ return (int)yyin->gcount();
+#endif
+}
+
+void yyFlexLexer::LexerOutput( const char* buf, int size )
+{
+ (void) yyout->write( buf, size );
+}
+%ok-for-header
+%endif
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/* yy_get_next_buffer - try to read in a new buffer
+ *
+ * Returns a code representing an action:
+ * EOB_ACT_LAST_MATCH -
+ * EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ * EOB_ACT_END_OF_FILE - end of file
+ */
+%if-c-only
+static int yy_get_next_buffer YYFARGS0(void)
+%endif
+%if-c++-only
+int yyFlexLexer::yy_get_next_buffer()
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+ register char *source = YY_G(yytext_ptr);
+ register int number_to_move, i;
+ int ret_val;
+
+ if ( YY_G(yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[YY_G(yy_n_chars) + 1] )
+ YY_FATAL_ERROR(
+ "fatal flex scanner internal error--end of buffer missed" );
+
+ if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+ { /* Don't try to fill the buffer, so this is an EOF. */
+ if ( YY_G(yy_c_buf_p) - YY_G(yytext_ptr) - YY_MORE_ADJ == 1 )
+ {
+ /* We matched a single character, the EOB, so
+ * treat this as a final EOF.
+ */
+ return EOB_ACT_END_OF_FILE;
+ }
+
+ else
+ {
+ /* We matched some text prior to the EOB, first
+ * process it.
+ */
+ return EOB_ACT_LAST_MATCH;
+ }
+ }
+
+ /* Try to read more data. */
+
+ /* First move last chars to start of buffer. */
+ number_to_move = (int) (YY_G(yy_c_buf_p) - YY_G(yytext_ptr)) - 1;
+
+ for ( i = 0; i < number_to_move; ++i )
+ *(dest++) = *(source++);
+
+ if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+ /* don't do the read, it's not guaranteed to return an EOF,
+ * just force an EOF
+ */
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = YY_G(yy_n_chars) = 0;
+
+ else
+ {
+ int num_to_read =
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+ while ( num_to_read <= 0 )
+ { /* Not enough room in the buffer - grow it. */
+m4_ifdef( [[M4_YY_USES_REJECT]],
+[[
+ YY_FATAL_ERROR(
+"input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
+]],
+[[
+ /* just a shorter name for the current buffer */
+ YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
+
+ int yy_c_buf_p_offset =
+ (int) (YY_G(yy_c_buf_p) - b->yy_ch_buf);
+
+ if ( b->yy_is_our_buffer )
+ {
+ int new_size = b->yy_buf_size * 2;
+
+ if ( new_size <= 0 )
+ b->yy_buf_size += b->yy_buf_size / 8;
+ else
+ b->yy_buf_size *= 2;
+
+ b->yy_ch_buf = (char *)
+ /* Include room in for 2 EOB chars. */
+ yyrealloc( (void *) b->yy_ch_buf,
+ b->yy_buf_size + 2 M4_YY_CALL_LAST_ARG );
+ }
+ else
+ /* Can't grow it, we don't own it. */
+ b->yy_ch_buf = 0;
+
+ if ( ! b->yy_ch_buf )
+ YY_FATAL_ERROR(
+ "fatal error - scanner input buffer overflow" );
+
+ YY_G(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+ num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+ number_to_move - 1;
+]])
+ }
+
+ if ( num_to_read > YY_READ_BUF_SIZE )
+ num_to_read = YY_READ_BUF_SIZE;
+
+ /* Read in more data. */
+ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+ YY_G(yy_n_chars), (size_t) num_to_read );
+
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = YY_G(yy_n_chars);
+ }
+
+ if ( YY_G(yy_n_chars) == 0 )
+ {
+ if ( number_to_move == YY_MORE_ADJ )
+ {
+ ret_val = EOB_ACT_END_OF_FILE;
+ yyrestart( yyin M4_YY_CALL_LAST_ARG);
+ }
+
+ else
+ {
+ ret_val = EOB_ACT_LAST_MATCH;
+ YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+ YY_BUFFER_EOF_PENDING;
+ }
+ }
+
+ else
+ ret_val = EOB_ACT_CONTINUE_SCAN;
+
+ if ((yy_size_t) (YY_G(yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+ /* Extend the array by 50%, plus the number we really need. */
+ yy_size_t new_size = YY_G(yy_n_chars) + number_to_move + (YY_G(yy_n_chars) >> 1);
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
+ (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, new_size M4_YY_CALL_LAST_ARG );
+ if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+ }
+
+ YY_G(yy_n_chars) += number_to_move;
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[YY_G(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[YY_G(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
+
+ YY_G(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
+
+ return ret_val;
+}
+]])
+
+/* yy_get_previous_state - get the state just before the EOB char was reached */
+
+%if-c-only
+%not-for-header
+ static yy_state_type yy_get_previous_state YYFARGS0(void)
+%endif
+%if-c++-only
+ yy_state_type yyFlexLexer::yy_get_previous_state()
+%endif
+{
+ register yy_state_type yy_current_state;
+ register char *yy_cp;
+ M4_YY_DECL_GUTS_VAR();
+
+%% [15.0] code to get the start state into yy_current_state goes here
+
+ for ( yy_cp = YY_G(yytext_ptr) + YY_MORE_ADJ; yy_cp < YY_G(yy_c_buf_p); ++yy_cp )
+ {
+%% [16.0] code to find the next state goes here
+ }
+
+ return yy_current_state;
+}
+
+
+/* yy_try_NUL_trans - try to make a transition on the NUL character
+ *
+ * synopsis
+ * next_state = yy_try_NUL_trans( current_state );
+ */
+%if-c-only
+ static yy_state_type yy_try_NUL_trans YYFARGS1( yy_state_type, yy_current_state)
+%endif
+%if-c++-only
+ yy_state_type yyFlexLexer::yy_try_NUL_trans( yy_state_type yy_current_state )
+%endif
+{
+ register int yy_is_jam;
+ M4_YY_DECL_GUTS_VAR(); /* This var may be unused depending upon options. */
+%% [17.0] code to find the next state, and perhaps do backing up, goes here
+
+ return yy_is_jam ? 0 : yy_current_state;
+}
+
+
+%if-c-only
+m4_ifdef( [[M4_YY_NO_UNPUT]],,
+[[
+ static void yyunput YYFARGS2( int,c, register char *,yy_bp)
+%endif
+%if-c++-only
+ void yyFlexLexer::yyunput( int c, register char* yy_bp)
+%endif
+{
+ register char *yy_cp;
+ M4_YY_DECL_GUTS_VAR();
+
+ yy_cp = YY_G(yy_c_buf_p);
+
+ /* undo effects of setting up yytext */
+ *yy_cp = YY_G(yy_hold_char);
+
+ if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+ { /* need to shift things up to make room */
+ /* +2 for EOB chars. */
+ register int number_to_move = YY_G(yy_n_chars) + 2;
+ register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
+ register char *source =
+ &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
+
+ while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+ *--dest = *--source;
+
+ yy_cp += (int) (dest - source);
+ yy_bp += (int) (dest - source);
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
+ YY_G(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+
+ if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+ YY_FATAL_ERROR( "flex scanner push-back overflow" );
+ }
+
+ *--yy_cp = (char) c;
+
+%% [18.0] update yylineno here
+m4_ifdef( [[M4_YY_USE_LINENO]],
+[[
+ if ( c == '\n' ){
+ --yylineno;
+ }
+]])
+
+ YY_G(yytext_ptr) = yy_bp;
+ YY_G(yy_hold_char) = *yy_cp;
+ YY_G(yy_c_buf_p) = yy_cp;
+}
+%if-c-only
+]])
+%endif
+
+%if-c-only
+#ifndef YY_NO_INPUT
+#ifdef __cplusplus
+ static int yyinput YYFARGS0(void)
+#else
+ static int input YYFARGS0(void)
+#endif
+
+%endif
+%if-c++-only
+ int yyFlexLexer::yyinput()
+%endif
+{
+ int c;
+ M4_YY_DECL_GUTS_VAR();
+
+ *YY_G(yy_c_buf_p) = YY_G(yy_hold_char);
+
+ if ( *YY_G(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
+ {
+ /* yy_c_buf_p now points to the character we want to return.
+ * If this occurs *before* the EOB characters, then it's a
+ * valid NUL; if not, then we've hit the end of the buffer.
+ */
+ if ( YY_G(yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[YY_G(yy_n_chars)] )
+ /* This was really a NUL. */
+ *YY_G(yy_c_buf_p) = '\0';
+
+ else
+ { /* need more input */
+ int offset = YY_G(yy_c_buf_p) - YY_G(yytext_ptr);
+ ++YY_G(yy_c_buf_p);
+
+ switch ( yy_get_next_buffer( M4_YY_CALL_ONLY_ARG ) )
+ {
+ case EOB_ACT_LAST_MATCH:
+ /* This happens because yy_g_n_b()
+ * sees that we've accumulated a
+ * token and flags that we need to
+ * try matching the token before
+ * proceeding. But for input(),
+ * there's no matching to consider.
+ * So convert the EOB_ACT_LAST_MATCH
+ * to EOB_ACT_END_OF_FILE.
+ */
+
+ /* Reset buffer status. */
+ yyrestart( yyin M4_YY_CALL_LAST_ARG);
+
+ /*FALLTHROUGH*/
+
+ case EOB_ACT_END_OF_FILE:
+ {
+ if ( yywrap( M4_YY_CALL_ONLY_ARG ) )
+ return EOF;
+
+ if ( ! YY_G(yy_did_buffer_switch_on_eof) )
+ YY_NEW_FILE;
+#ifdef __cplusplus
+ return yyinput(M4_YY_CALL_ONLY_ARG);
+#else
+ return input(M4_YY_CALL_ONLY_ARG);
+#endif
+ }
+
+ case EOB_ACT_CONTINUE_SCAN:
+ YY_G(yy_c_buf_p) = YY_G(yytext_ptr) + offset;
+ break;
+ }
+ }
+ }
+
+ c = *(unsigned char *) YY_G(yy_c_buf_p); /* cast for 8-bit char's */
+ *YY_G(yy_c_buf_p) = '\0'; /* preserve yytext */
+ YY_G(yy_hold_char) = *++YY_G(yy_c_buf_p);
+
+%% [19.0] update BOL and yylineno
+
+ return c;
+}
+%if-c-only
+#endif /* ifndef YY_NO_INPUT */
+%endif
+
+/** Immediately switch to a different input stream.
+ * @param input_file A readable stream.
+ * M4_YY_DOC_PARAM
+ * @note This function does not reset the start condition to @c INITIAL .
+ */
+%if-c-only
+ void yyrestart YYFARGS1( FILE *,input_file)
+%endif
+%if-c++-only
+ void yyFlexLexer::yyrestart( std::istream* input_file )
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ if ( ! YY_CURRENT_BUFFER ){
+ yyensure_buffer_stack (M4_YY_CALL_ONLY_ARG);
+ YY_CURRENT_BUFFER_LVALUE =
+ yy_create_buffer( yyin, YY_BUF_SIZE M4_YY_CALL_LAST_ARG);
+ }
+
+ yy_init_buffer( YY_CURRENT_BUFFER, input_file M4_YY_CALL_LAST_ARG);
+ yy_load_buffer_state( M4_YY_CALL_ONLY_ARG );
+}
+
+/** Switch to a different input buffer.
+ * @param new_buffer The new input buffer.
+ * M4_YY_DOC_PARAM
+ */
+%if-c-only
+ void yy_switch_to_buffer YYFARGS1( YY_BUFFER_STATE ,new_buffer)
+%endif
+%if-c++-only
+ void yyFlexLexer::yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ /* TODO. We should be able to replace this entire function body
+ * with
+ * yypop_buffer_state();
+ * yypush_buffer_state(new_buffer);
+ */
+ yyensure_buffer_stack (M4_YY_CALL_ONLY_ARG);
+ if ( YY_CURRENT_BUFFER == new_buffer )
+ return;
+
+ if ( YY_CURRENT_BUFFER )
+ {
+ /* Flush out information for old buffer. */
+ *YY_G(yy_c_buf_p) = YY_G(yy_hold_char);
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = YY_G(yy_c_buf_p);
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = YY_G(yy_n_chars);
+ }
+
+ YY_CURRENT_BUFFER_LVALUE = new_buffer;
+ yy_load_buffer_state( M4_YY_CALL_ONLY_ARG );
+
+ /* We don't actually know whether we did this switch during
+ * EOF (yywrap()) processing, but the only time this flag
+ * is looked at is after yywrap() is called, so it's safe
+ * to go ahead and always set it.
+ */
+ YY_G(yy_did_buffer_switch_on_eof) = 1;
+}
+
+
+%if-c-only
+static void yy_load_buffer_state YYFARGS0(void)
+%endif
+%if-c++-only
+ void yyFlexLexer::yy_load_buffer_state()
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ YY_G(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+ YY_G(yytext_ptr) = YY_G(yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+ yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+ YY_G(yy_hold_char) = *YY_G(yy_c_buf_p);
+}
+
+/** Allocate and initialize an input buffer state.
+ * @param file A readable stream.
+ * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
+ * M4_YY_DOC_PARAM
+ * @return the allocated buffer state.
+ */
+%if-c-only
+ YY_BUFFER_STATE yy_create_buffer YYFARGS2( FILE *,file, int ,size)
+%endif
+%if-c++-only
+ YY_BUFFER_STATE yyFlexLexer::yy_create_buffer( std::istream* file, int size )
+%endif
+{
+ YY_BUFFER_STATE b;
+ m4_dnl M4_YY_DECL_GUTS_VAR();
+
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) M4_YY_CALL_LAST_ARG );
+ if ( ! b )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+ b->yy_buf_size = size;
+
+ /* yy_ch_buf has to be 2 characters longer than the size given because
+ * we need to put in 2 end-of-buffer characters.
+ */
+ b->yy_ch_buf = (char *) yyalloc( b->yy_buf_size + 2 M4_YY_CALL_LAST_ARG );
+ if ( ! b->yy_ch_buf )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+ b->yy_is_our_buffer = 1;
+
+ yy_init_buffer( b, file M4_YY_CALL_LAST_ARG);
+
+ return b;
+}
+
+/** Destroy the buffer.
+ * @param b a buffer created with yy_create_buffer()
+ * M4_YY_DOC_PARAM
+ */
+%if-c-only
+ void yy_delete_buffer YYFARGS1( YY_BUFFER_STATE ,b)
+%endif
+%if-c++-only
+ void yyFlexLexer::yy_delete_buffer( YY_BUFFER_STATE b )
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ if ( ! b )
+ return;
+
+ if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+
+ if ( b->yy_is_our_buffer )
+ yyfree( (void *) b->yy_ch_buf M4_YY_CALL_LAST_ARG );
+
+ yyfree( (void *) b M4_YY_CALL_LAST_ARG );
+}
+
+
+%if-c-only
+m4_ifdef( [[M4_YY_ALWAYS_INTERACTIVE]],,
+[[
+ m4_ifdef( [[M4_YY_NEVER_INTERACTIVE]],,
+ [[
+#ifndef __cplusplus
+extern int isatty M4_YY_PARAMS( int );
+#endif /* __cplusplus */
+ ]])
+]])
+%endif
+
+%if-c++-only
+m4_ifdef( [[M4_YY_NEVER_INTERACTIVE]],,
+[[
+]])
+%endif
+
+/* Initializes or reinitializes a buffer.
+ * This function is sometimes called more than once on the same buffer,
+ * such as during a yyrestart() or at EOF.
+ */
+%if-c-only
+ static void yy_init_buffer YYFARGS2( YY_BUFFER_STATE ,b, FILE *,file)
+%endif
+%if-c++-only
+ void yyFlexLexer::yy_init_buffer( YY_BUFFER_STATE b, std::istream* file )
+%endif
+
+{
+ int oerrno = errno;
+ M4_YY_DECL_GUTS_VAR();
+
+ yy_flush_buffer( b M4_YY_CALL_LAST_ARG);
+
+ b->yy_input_file = file;
+ b->yy_fill_buffer = 1;
+
+ /* If b is the current buffer, then yy_init_buffer was _probably_
+ * called from yyrestart() or through yy_get_next_buffer.
+ * In that case, we don't want to reset the lineno or column.
+ */
+ if (b != YY_CURRENT_BUFFER){
+ b->yy_bs_lineno = 1;
+ b->yy_bs_column = 0;
+ }
+
+%if-c-only
+m4_ifdef( [[M4_YY_ALWAYS_INTERACTIVE]],
+[[
+ b->yy_is_interactive = 1;
+]],
+[[
+ m4_ifdef( [[M4_YY_NEVER_INTERACTIVE]],
+ [[
+ b->yy_is_interactive = 0;
+ ]],
+ [[
+ b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
+ ]])
+]])
+%endif
+%if-c++-only
+ b->yy_is_interactive = 0;
+%endif
+ errno = oerrno;
+}
+
+/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
+ * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
+ * M4_YY_DOC_PARAM
+ */
+%if-c-only
+ void yy_flush_buffer YYFARGS1( YY_BUFFER_STATE ,b)
+%endif
+%if-c++-only
+ void yyFlexLexer::yy_flush_buffer( YY_BUFFER_STATE b )
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ if ( ! b )
+ return;
+
+ b->yy_n_chars = 0;
+
+ /* We always need two end-of-buffer characters. The first causes
+ * a transition to the end-of-buffer state. The second causes
+ * a jam in that state.
+ */
+ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+ b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+
+ b->yy_buf_pos = &b->yy_ch_buf[0];
+
+ b->yy_at_bol = 1;
+ b->yy_buffer_status = YY_BUFFER_NEW;
+
+ if ( b == YY_CURRENT_BUFFER )
+ yy_load_buffer_state( M4_YY_CALL_ONLY_ARG );
+}
+
+%if-c-or-c++
+/** Pushes the new state onto the stack. The new state becomes
+ * the current state. This function will allocate the stack
+ * if necessary.
+ * @param new_buffer The new state.
+ * M4_YY_DOC_PARAM
+ */
+%if-c-only
+void yypush_buffer_state YYFARGS1(YY_BUFFER_STATE,new_buffer)
+%endif
+%if-c++-only
+void yyFlexLexer::yypush_buffer_state (YY_BUFFER_STATE new_buffer)
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ if (new_buffer == NULL)
+ return;
+
+ yyensure_buffer_stack(M4_YY_CALL_ONLY_ARG);
+
+ /* This block is copied from yy_switch_to_buffer. */
+ if ( YY_CURRENT_BUFFER )
+ {
+ /* Flush out information for old buffer. */
+ *YY_G(yy_c_buf_p) = YY_G(yy_hold_char);
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = YY_G(yy_c_buf_p);
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = YY_G(yy_n_chars);
+ }
+
+ /* Only push if top exists. Otherwise, replace top. */
+ if (YY_CURRENT_BUFFER)
+ YY_G(yy_buffer_stack_top)++;
+ YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+ /* copied from yy_switch_to_buffer. */
+ yy_load_buffer_state( M4_YY_CALL_ONLY_ARG );
+ YY_G(yy_did_buffer_switch_on_eof) = 1;
+}
+%endif
+
+
+%if-c-or-c++
+/** Removes and deletes the top of the stack, if present.
+ * The next element becomes the new top.
+ * M4_YY_DOC_PARAM
+ */
+%if-c-only
+void yypop_buffer_state YYFARGS0(void)
+%endif
+%if-c++-only
+void yyFlexLexer::yypop_buffer_state (void)
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ if (!YY_CURRENT_BUFFER)
+ return;
+
+ yy_delete_buffer(YY_CURRENT_BUFFER M4_YY_CALL_LAST_ARG);
+ YY_CURRENT_BUFFER_LVALUE = NULL;
+ if (YY_G(yy_buffer_stack_top) > 0)
+ --YY_G(yy_buffer_stack_top);
+
+ if (YY_CURRENT_BUFFER) {
+ yy_load_buffer_state( M4_YY_CALL_ONLY_ARG );
+ YY_G(yy_did_buffer_switch_on_eof) = 1;
+ }
+}
+%endif
+
+
+%if-c-or-c++
+/* Allocates the stack if it does not exist.
+ * Guarantees space for at least one push.
+ */
+%if-c-only
+static void yyensure_buffer_stack YYFARGS0(void)
+%endif
+%if-c++-only
+void yyFlexLexer::yyensure_buffer_stack(void)
+%endif
+{
+ int num_to_alloc;
+ M4_YY_DECL_GUTS_VAR();
+
+ if (!YY_G(yy_buffer_stack)) {
+
+ /* First allocation is just for 2 elements, since we don't know if this
+ * scanner will even need a stack. We use 2 instead of 1 to avoid an
+ * immediate realloc on the next call.
+ */
+ num_to_alloc = 1;
+ YY_G(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
+ (num_to_alloc * sizeof(struct yy_buffer_state*)
+ M4_YY_CALL_LAST_ARG);
+ if ( ! YY_G(yy_buffer_stack) )
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
+
+
+ memset(YY_G(yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+
+ YY_G(yy_buffer_stack_max) = num_to_alloc;
+ YY_G(yy_buffer_stack_top) = 0;
+ return;
+ }
+
+ if (YY_G(yy_buffer_stack_top) >= (YY_G(yy_buffer_stack_max)) - 1){
+
+ /* Increase the buffer to prepare for a possible push. */
+ int grow_size = 8 /* arbitrary grow size */;
+
+ num_to_alloc = YY_G(yy_buffer_stack_max) + grow_size;
+ YY_G(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
+ (YY_G(yy_buffer_stack),
+ num_to_alloc * sizeof(struct yy_buffer_state*)
+ M4_YY_CALL_LAST_ARG);
+ if ( ! YY_G(yy_buffer_stack) )
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
+
+ /* zero only the new slots.*/
+ memset(YY_G(yy_buffer_stack) + YY_G(yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
+ YY_G(yy_buffer_stack_max) = num_to_alloc;
+ }
+}
+%endif
+
+
+
+
+m4_ifdef( [[M4_YY_NO_SCAN_BUFFER]],,
+[[
+%if-c-only
+/** Setup the input buffer state to scan directly from a user-specified character buffer.
+ * @param base the character buffer
+ * @param size the size in bytes of the character buffer
+ * M4_YY_DOC_PARAM
+ * @return the newly allocated buffer state object.
+ */
+YY_BUFFER_STATE yy_scan_buffer YYFARGS2( char *,base, yy_size_t ,size)
+{
+ YY_BUFFER_STATE b;
+ m4_dnl M4_YY_DECL_GUTS_VAR();
+
+ if ( size < 2 ||
+ base[size-2] != YY_END_OF_BUFFER_CHAR ||
+ base[size-1] != YY_END_OF_BUFFER_CHAR )
+ /* They forgot to leave room for the EOB's. */
+ return 0;
+
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) M4_YY_CALL_LAST_ARG );
+ if ( ! b )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
+
+ b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
+ b->yy_buf_pos = b->yy_ch_buf = base;
+ b->yy_is_our_buffer = 0;
+ b->yy_input_file = 0;
+ b->yy_n_chars = b->yy_buf_size;
+ b->yy_is_interactive = 0;
+ b->yy_at_bol = 1;
+ b->yy_fill_buffer = 0;
+ b->yy_buffer_status = YY_BUFFER_NEW;
+
+ yy_switch_to_buffer( b M4_YY_CALL_LAST_ARG );
+
+ return b;
+}
+%endif
+]])
+
+
+m4_ifdef( [[M4_YY_NO_SCAN_STRING]],,
+[[
+%if-c-only
+/** Setup the input buffer state to scan a string. The next call to yylex() will
+ * scan from a @e copy of @a str.
+ * @param yystr a NUL-terminated string to scan
+ * M4_YY_DOC_PARAM
+ * @return the newly allocated buffer state object.
+ * @note If you want to scan bytes that may contain NUL values, then use
+ * yy_scan_bytes() instead.
+ */
+YY_BUFFER_STATE yy_scan_string YYFARGS1( yyconst char *, yystr)
+{
+ m4_dnl M4_YY_DECL_GUTS_VAR();
+
+ return yy_scan_bytes( yystr, strlen(yystr) M4_YY_CALL_LAST_ARG);
+}
+%endif
+]])
+
+
+m4_ifdef( [[M4_YY_NO_SCAN_BYTES]],,
+[[
+%if-c-only
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
+ * scan from a @e copy of @a bytes.
+ * @param bytes the byte buffer to scan
+ * @param len the number of bytes in the buffer pointed to by @a bytes.
+ * M4_YY_DOC_PARAM
+ * @return the newly allocated buffer state object.
+ */
+YY_BUFFER_STATE yy_scan_bytes YYFARGS2( yyconst char *,yybytes, int ,_yybytes_len)
+{
+ YY_BUFFER_STATE b;
+ char *buf;
+ yy_size_t n;
+ int i;
+ m4_dnl M4_YY_DECL_GUTS_VAR();
+
+ /* Get memory for full buffer, including space for trailing EOB's. */
+ n = _yybytes_len + 2;
+ buf = (char *) yyalloc( n M4_YY_CALL_LAST_ARG );
+ if ( ! buf )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
+
+ for ( i = 0; i < _yybytes_len; ++i )
+ buf[i] = yybytes[i];
+
+ buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
+
+ b = yy_scan_buffer( buf, n M4_YY_CALL_LAST_ARG);
+ if ( ! b )
+ YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
+
+ /* It's okay to grow etc. this buffer, and we should throw it
+ * away when we're done.
+ */
+ b->yy_is_our_buffer = 1;
+
+ return b;
+}
+%endif
+]])
+
+
+m4_ifdef( [[M4_YY_NO_PUSH_STATE]],,
+[[
+%if-c-only
+ static void yy_push_state YYFARGS1( int ,new_state)
+%endif
+%if-c++-only
+ void yyFlexLexer::yy_push_state( int new_state )
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ if ( YY_G(yy_start_stack_ptr) >= YY_G(yy_start_stack_depth) )
+ {
+ yy_size_t new_size;
+
+ YY_G(yy_start_stack_depth) += YY_START_STACK_INCR;
+ new_size = YY_G(yy_start_stack_depth) * sizeof( int );
+
+ if ( ! YY_G(yy_start_stack) )
+ YY_G(yy_start_stack) = (int *) yyalloc( new_size M4_YY_CALL_LAST_ARG );
+
+ else
+ YY_G(yy_start_stack) = (int *) yyrealloc(
+ (void *) YY_G(yy_start_stack), new_size M4_YY_CALL_LAST_ARG );
+
+ if ( ! YY_G(yy_start_stack) )
+ YY_FATAL_ERROR( "out of memory expanding start-condition stack" );
+ }
+
+ YY_G(yy_start_stack)[YY_G(yy_start_stack_ptr)++] = YY_START;
+
+ BEGIN(new_state);
+}
+]])
+
+
+m4_ifdef( [[M4_YY_NO_POP_STATE]],,
+[[
+%if-c-only
+ static void yy_pop_state YYFARGS0(void)
+%endif
+%if-c++-only
+ void yyFlexLexer::yy_pop_state()
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ if ( --YY_G(yy_start_stack_ptr) < 0 )
+ YY_FATAL_ERROR( "start-condition stack underflow" );
+
+ BEGIN(YY_G(yy_start_stack)[YY_G(yy_start_stack_ptr)]);
+}
+]])
+
+
+m4_ifdef( [[M4_YY_NO_TOP_STATE]],,
+[[
+%if-c-only
+ static int yy_top_state YYFARGS0(void)
+%endif
+%if-c++-only
+ int yyFlexLexer::yy_top_state()
+%endif
+{
+ M4_YY_DECL_GUTS_VAR();
+ return YY_G(yy_start_stack)[YY_G(yy_start_stack_ptr) - 1];
+}
+]])
+
+#ifndef YY_EXIT_FAILURE
+#define YY_EXIT_FAILURE 2
+#endif
+
+%if-c-only
+static void yy_fatal_error YYFARGS1(yyconst char*, msg)
+{
+ m4_dnl M4_YY_DECL_GUTS_VAR();
+ (void) fprintf( stderr, "%s\n", msg );
+ exit( YY_EXIT_FAILURE );
+}
+%endif
+%if-c++-only
+void yyFlexLexer::LexerError( yyconst char msg[] )
+{
+ M4_YY_DECL_GUTS_VAR();
+ std::cerr << msg << std::endl;
+ exit( YY_EXIT_FAILURE );
+}
+%endif
+
+/* Redefine yyless() so it works in section 3 code. */
+
+#undef yyless
+#define yyless(n) \
+ do \
+ { \
+ /* Undo effects of setting up yytext. */ \
+ int yyless_macro_arg = (n); \
+ YY_LESS_LINENO(yyless_macro_arg);\
+ yytext[yyleng] = YY_G(yy_hold_char); \
+ YY_G(yy_c_buf_p) = yytext + yyless_macro_arg; \
+ YY_G(yy_hold_char) = *YY_G(yy_c_buf_p); \
+ *YY_G(yy_c_buf_p) = '\0'; \
+ yyleng = yyless_macro_arg; \
+ } \
+ while ( 0 )
+
+
+
+/* Accessor methods (get/set functions) to struct members. */
+
+%if-c-only
+%if-reentrant
+m4_ifdef( [[M4_YY_NO_GET_EXTRA]],,
+[[
+/** Get the user-defined data for this scanner.
+ * M4_YY_DOC_PARAM
+ */
+YY_EXTRA_TYPE yyget_extra YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yyextra;
+}
+]])
+%endif
+
+m4_ifdef( [[M4_YY_NO_GET_LINENO]],,
+[[
+/** Get the current line number.
+ * M4_YY_DOC_PARAM
+ */
+int yyget_lineno YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ m4_ifdef( [[M4_YY_REENTRANT]],
+ [[
+ if (! YY_CURRENT_BUFFER)
+ return 0;
+ ]])
+ return yylineno;
+}
+]])
+
+m4_ifdef( [[M4_YY_REENTRANT]],
+[[
+m4_ifdef( [[M4_YY_NO_GET_COLUMN]],,
+[[
+/** Get the current column number.
+ * M4_YY_DOC_PARAM
+ */
+int yyget_column YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ m4_ifdef( [[M4_YY_REENTRANT]],
+ [[
+ if (! YY_CURRENT_BUFFER)
+ return 0;
+ ]])
+ return yycolumn;
+}
+]])
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_IN]],,
+[[
+/** Get the input stream.
+ * M4_YY_DOC_PARAM
+ */
+FILE *yyget_in YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yyin;
+}
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_OUT]],,
+[[
+/** Get the output stream.
+ * M4_YY_DOC_PARAM
+ */
+FILE *yyget_out YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yyout;
+}
+]])
+
+m4_ifdef( [[M4_YY_NO_GET_LENG]],,
+[[
+/** Get the length of the current token.
+ * M4_YY_DOC_PARAM
+ */
+int yyget_leng YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yyleng;
+}
+]])
+
+/** Get the current token.
+ * M4_YY_DOC_PARAM
+ */
+m4_ifdef( [[M4_YY_NO_GET_TEXT]],,
+[[
+char *yyget_text YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yytext;
+}
+]])
+
+%if-reentrant
+m4_ifdef( [[M4_YY_NO_SET_EXTRA]],,
+[[
+/** Set the user-defined data. This data is never touched by the scanner.
+ * @param user_defined The data to be associated with this scanner.
+ * M4_YY_DOC_PARAM
+ */
+void yyset_extra YYFARGS1( YY_EXTRA_TYPE ,user_defined)
+{
+ M4_YY_DECL_GUTS_VAR();
+ yyextra = user_defined ;
+}
+]])
+%endif
+
+m4_ifdef( [[M4_YY_NO_SET_LINENO]],,
+[[
+/** Set the current line number.
+ * @param line_number
+ * M4_YY_DOC_PARAM
+ */
+void yyset_lineno YYFARGS1( int ,line_number)
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ m4_ifdef( [[M4_YY_REENTRANT]],
+ [[
+ /* lineno is only valid if an input buffer exists. */
+ if (! YY_CURRENT_BUFFER )
+ yy_fatal_error( "yyset_lineno called with no buffer" M4_YY_CALL_LAST_ARG);
+ ]])
+ yylineno = line_number;
+}
+]])
+
+m4_ifdef( [[M4_YY_REENTRANT]],
+[[
+m4_ifdef( [[M4_YY_NO_SET_COLUMN]],,
+[[
+/** Set the current column.
+ * @param line_number
+ * M4_YY_DOC_PARAM
+ */
+void yyset_column YYFARGS1( int , column_no)
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ m4_ifdef( [[M4_YY_REENTRANT]],
+ [[
+ /* column is only valid if an input buffer exists. */
+ if (! YY_CURRENT_BUFFER )
+ yy_fatal_error( "yyset_column called with no buffer" M4_YY_CALL_LAST_ARG);
+ ]])
+ yycolumn = column_no;
+}
+]])
+]])
+
+
+m4_ifdef( [[M4_YY_NO_SET_IN]],,
+[[
+/** Set the input stream. This does not discard the current
+ * input buffer.
+ * @param in_str A readable stream.
+ * M4_YY_DOC_PARAM
+ * @see yy_switch_to_buffer
+ */
+void yyset_in YYFARGS1( FILE * ,in_str)
+{
+ M4_YY_DECL_GUTS_VAR();
+ yyin = in_str ;
+}
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_OUT]],,
+[[
+void yyset_out YYFARGS1( FILE * ,out_str)
+{
+ M4_YY_DECL_GUTS_VAR();
+ yyout = out_str ;
+}
+]])
+
+
+m4_ifdef( [[M4_YY_NO_GET_DEBUG]],,
+[[
+int yyget_debug YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yy_flex_debug;
+}
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_DEBUG]],,
+[[
+void yyset_debug YYFARGS1( int ,bdebug)
+{
+ M4_YY_DECL_GUTS_VAR();
+ yy_flex_debug = bdebug ;
+}
+]])
+%endif
+
+%if-reentrant
+/* Accessor methods for yylval and yylloc */
+
+%if-bison-bridge
+m4_ifdef( [[M4_YY_NO_GET_LVAL]],,
+[[
+YYSTYPE * yyget_lval YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yylval;
+}
+]])
+
+m4_ifdef( [[M4_YY_NO_SET_LVAL]],,
+[[
+void yyset_lval YYFARGS1( YYSTYPE * ,yylval_param)
+{
+ M4_YY_DECL_GUTS_VAR();
+ yylval = yylval_param;
+}
+]])
+
+m4_ifdef( [[<M4_YY_BISON_LLOC>]],
+[[
+ m4_ifdef( [[M4_YY_NO_GET_LLOC]],,
+ [[
+YYLTYPE *yyget_lloc YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ return yylloc;
+}
+ ]])
+
+ m4_ifdef( [[M4_YY_NO_SET_LLOC]],,
+ [[
+void yyset_lloc YYFARGS1( YYLTYPE * ,yylloc_param)
+{
+ M4_YY_DECL_GUTS_VAR();
+ yylloc = yylloc_param;
+}
+ ]])
+]])
+
+%endif
+
+
+/* User-visible API */
+
+/* yylex_init is special because it creates the scanner itself, so it is
+ * the ONLY reentrant function that doesn't take the scanner as the last argument.
+ * That's why we explicitly handle the declaration, instead of using our macros.
+ */
+m4_ifdef( [[M4_YY_NO_ANSI_FUNC_DEFS]],
+[[
+int yylex_init( ptr_yy_globals )
+ yyscan_t* ptr_yy_globals;
+]],
+[[
+int yylex_init(yyscan_t* ptr_yy_globals)
+]])
+{
+ if (ptr_yy_globals == NULL){
+ errno = EINVAL;
+ return 1;
+ }
+
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
+
+ if (*ptr_yy_globals == NULL){
+ errno = ENOMEM;
+ return 1;
+ }
+
+ /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
+ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
+
+ return yy_init_globals ( *ptr_yy_globals );
+}
+
+
+/* yylex_init_extra has the same functionality as yylex_init, but follows the
+ * convention of taking the scanner as the last argument. Note however, that
+ * this is a *pointer* to a scanner, as it will be allocated by this call (and
+ * is the reason, too, why this function also must handle its own declaration).
+ * The user defined value in the first argument will be available to yyalloc in
+ * the yyextra field.
+ */
+m4_ifdef( [[M4_YY_NO_ANSI_FUNC_DEFS]],
+[[
+int yylex_init_extra( yy_user_defined, ptr_yy_globals )
+ YY_EXTRA_TYPE yy_user_defined;
+ yyscan_t* ptr_yy_globals;
+]],
+[[
+int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals )
+]])
+{
+ struct yyguts_t dummy_yyguts;
+
+ yyset_extra (yy_user_defined, &dummy_yyguts);
+
+ if (ptr_yy_globals == NULL){
+ errno = EINVAL;
+ return 1;
+ }
+
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+
+ if (*ptr_yy_globals == NULL){
+ errno = ENOMEM;
+ return 1;
+ }
+
+ /* By setting to 0xAA, we expose bugs in
+ yy_init_globals. Leave at 0x00 for releases. */
+ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
+
+ yyset_extra (yy_user_defined, *ptr_yy_globals);
+
+ return yy_init_globals ( *ptr_yy_globals );
+}
+
+%endif if-c-only
+
+
+%if-c-only
+static int yy_init_globals YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+ /* Initialization is the same as for the non-reentrant scanner.
+ * This function is called from yylex_destroy(), so don't allocate here.
+ */
+
+m4_ifdef( [[M4_YY_USE_LINENO]],
+[[
+ m4_ifdef( [[M4_YY_NOT_REENTRANT]],
+ [[
+ /* We do not touch yylineno unless the option is enabled. */
+ yylineno = 1;
+ ]])
+]])
+ YY_G(yy_buffer_stack) = 0;
+ YY_G(yy_buffer_stack_top) = 0;
+ YY_G(yy_buffer_stack_max) = 0;
+ YY_G(yy_c_buf_p) = (char *) 0;
+ YY_G(yy_init) = 0;
+ YY_G(yy_start) = 0;
+
+m4_ifdef( [[M4_YY_HAS_START_STACK_VARS]],
+[[
+ YY_G(yy_start_stack_ptr) = 0;
+ YY_G(yy_start_stack_depth) = 0;
+ YY_G(yy_start_stack) = NULL;
+]])
+
+m4_ifdef( [[M4_YY_USES_REJECT]],
+[[
+ YY_G(yy_state_buf) = 0;
+ YY_G(yy_state_ptr) = 0;
+ YY_G(yy_full_match) = 0;
+ YY_G(yy_lp) = 0;
+]])
+
+m4_ifdef( [[M4_YY_TEXT_IS_ARRAY]],
+[[
+ YY_G(yytext_ptr) = 0;
+ YY_G(yy_more_offset) = 0;
+ YY_G(yy_prev_more_offset) = 0;
+]])
+
+/* Defined in main.c */
+#ifdef YY_STDINIT
+ yyin = stdin;
+ yyout = stdout;
+#else
+ yyin = (FILE *) 0;
+ yyout = (FILE *) 0;
+#endif
+
+ /* For future reference: Set errno on error, since we are called by
+ * yylex_init()
+ */
+ return 0;
+}
+%endif
+
+
+%if-c-only SNIP! this currently causes conflicts with the c++ scanner
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy YYFARGS0(void)
+{
+ M4_YY_DECL_GUTS_VAR();
+
+ /* Pop the buffer stack, destroying each element. */
+ while(YY_CURRENT_BUFFER){
+ yy_delete_buffer( YY_CURRENT_BUFFER M4_YY_CALL_LAST_ARG );
+ YY_CURRENT_BUFFER_LVALUE = NULL;
+ yypop_buffer_state(M4_YY_CALL_ONLY_ARG);
+ }
+
+ /* Destroy the stack itself. */
+ yyfree(YY_G(yy_buffer_stack) M4_YY_CALL_LAST_ARG);
+ YY_G(yy_buffer_stack) = NULL;
+
+m4_ifdef( [[M4_YY_HAS_START_STACK_VARS]],
+[[
+ /* Destroy the start condition stack. */
+ yyfree( YY_G(yy_start_stack) M4_YY_CALL_LAST_ARG );
+ YY_G(yy_start_stack) = NULL;
+]])
+
+m4_ifdef( [[M4_YY_USES_REJECT]],
+[[
+ yyfree ( YY_G(yy_state_buf) M4_YY_CALL_LAST_ARG);
+ YY_G(yy_state_buf) = NULL;
+]])
+
+ /* Reset the globals. This is important in a non-reentrant scanner so the next time
+ * yylex() is called, initialization will occur. */
+ yy_init_globals( M4_YY_CALL_ONLY_ARG);
+
+%if-reentrant
+ /* Destroy the main struct (reentrant only). */
+ yyfree ( yyscanner M4_YY_CALL_LAST_ARG );
+ yyscanner = NULL;
+%endif
+ return 0;
+}
+%endif
+
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+/*
+ * Internal utility routines.
+ */
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#ifndef yytext_ptr
+static void yy_flex_strncpy YYFARGS3( char*,s1, yyconst char *,s2, int,n)
+{
+ register int i;
+ for ( i = 0; i < n; ++i )
+ s1[i] = s2[i];
+}
+#endif
+]])
+
+m4_ifdef( [[M4_YY_NOT_IN_HEADER]],
+[[
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen YYFARGS1( yyconst char *,s)
+{
+ register int n;
+ for ( n = 0; s[n]; ++n )
+ ;
+
+ return n;
+}
+#endif
+]])
+
+m4_ifdef( [[M4_YY_NO_FLEX_ALLOC]],,
+[[
+void *yyalloc YYFARGS1( yy_size_t ,size)
+{
+ return (void *) malloc( size );
+}
+]])
+
+m4_ifdef( [[M4_YY_NO_FLEX_REALLOC]],,
+[[
+void *yyrealloc YYFARGS2( void *,ptr, yy_size_t ,size)
+{
+ /* The cast to (char *) in the following accommodates both
+ * implementations that use char* generic pointers, and those
+ * that use void* generic pointers. It works with the latter
+ * because both ANSI C and C++ allow castless assignment from
+ * any pointer type to void*, and deal with argument conversions
+ * as though doing an assignment.
+ */
+ return (void *) realloc( (char *) ptr, size );
+}
+]])
+
+m4_ifdef( [[M4_YY_NO_FLEX_FREE]],,
+[[
+void yyfree YYFARGS1( void *,ptr)
+{
+ free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
+}
+]])
+
+%if-tables-serialization definitions
+m4preproc_include(`tables_shared.c')
+
+static int yytbl_read8 (void *v, struct yytbl_reader * rd)
+{
+ errno = 0;
+ if (fread (v, sizeof (flex_uint8_t), 1, rd->fp) != 1){
+ errno = EIO;
+ return -1;
+ }
+ rd->bread += sizeof(flex_uint8_t);
+ return 0;
+}
+
+static int yytbl_read16 (void *v, struct yytbl_reader * rd)
+{
+ errno = 0;
+ if (fread (v, sizeof (flex_uint16_t), 1, rd->fp) != 1){
+ errno = EIO;
+ return -1;
+ }
+ *((flex_uint16_t *) v) = ntohs (*((flex_uint16_t *) v));
+ rd->bread += sizeof(flex_uint16_t);
+ return 0;
+}
+
+static int yytbl_read32 (void *v, struct yytbl_reader * rd)
+{
+ errno = 0;
+ if (fread (v, sizeof (flex_uint32_t), 1, rd->fp) != 1){
+ errno = EIO;
+ return -1;
+ }
+ *((flex_uint32_t *) v) = ntohl (*((flex_uint32_t *) v));
+ rd->bread += sizeof(flex_uint32_t);
+ return 0;
+}
+
+/** Read the header */
+static int yytbl_hdr_read YYFARGS2(struct yytbl_hdr *, th, struct yytbl_reader *, rd)
+{
+ int bytes;
+ memset (th, 0, sizeof (struct yytbl_hdr));
+
+ if (yytbl_read32 (&(th->th_magic), rd) != 0)
+ return -1;
+
+ if (th->th_magic != YYTBL_MAGIC){
+ yy_fatal_error("bad magic number" /*TODO: not fatal.*/ M4_YY_CALL_LAST_ARG);
+ return -1;
+ }
+
+ if (yytbl_read32 (&(th->th_hsize), rd) != 0
+ || yytbl_read32 (&(th->th_ssize), rd) != 0
+ || yytbl_read16 (&(th->th_flags), rd) != 0)
+ return -1;
+
+ /* Sanity check on header size. Greater than 1k suggests some funny business. */
+ if (th->th_hsize < 16 || th->th_hsize > 1024){
+ yy_fatal_error("insane header size detected" /*TODO: not fatal.*/ M4_YY_CALL_LAST_ARG);
+ return -1;
+ }
+
+ /* Allocate enough space for the version and name fields */
+ bytes = th->th_hsize - 14;
+ th->th_version = (char *) yyalloc (bytes M4_YY_CALL_LAST_ARG);
+ if ( ! th->th_version )
+ YY_FATAL_ERROR( "out of dynamic memory in yytbl_hdr_read()" );
+
+ /* we read it all into th_version, and point th_name into that data */
+ if (fread (th->th_version, 1, bytes, rd->fp) != bytes){
+ errno = EIO;
+ yyfree(th->th_version M4_YY_CALL_LAST_ARG);
+ th->th_version = NULL;
+ return -1;
+ }
+ else
+ rd->bread += bytes;
+
+ th->th_name = th->th_version + strlen (th->th_version) + 1;
+ return 0;
+}
+
+/** lookup id in the dmap list.
+ * @param dmap pointer to first element in list
+ * @return NULL if not found.
+ */
+static struct yytbl_dmap *yytbl_dmap_lookup YYFARGS2(struct yytbl_dmap *, dmap,
+ int, id)
+{
+ while (dmap->dm_id)
+ if (dmap->dm_id == id)
+ return dmap;
+ else
+ dmap++;
+ return NULL;
+}
+
+/** Read a table while mapping its contents to the local array.
+ * @param dmap used to performing mapping
+ * @return 0 on success
+ */
+static int yytbl_data_load YYFARGS2(struct yytbl_dmap *, dmap, struct yytbl_reader*, rd)
+{
+ struct yytbl_data td;
+ struct yytbl_dmap *transdmap=0;
+ int len, i, rv, inner_loop_count;
+ void *p=0;
+
+ memset (&td, 0, sizeof (struct yytbl_data));
+
+ if (yytbl_read16 (&td.td_id, rd) != 0
+ || yytbl_read16 (&td.td_flags, rd) != 0
+ || yytbl_read32 (&td.td_hilen, rd) != 0
+ || yytbl_read32 (&td.td_lolen, rd) != 0)
+ return -1;
+
+ /* Lookup the map for the transition table so we have it in case we need it
+ * inside the loop below. This scanner might not even have a transition
+ * table, which is ok.
+ */
+ transdmap = yytbl_dmap_lookup (dmap, YYTD_ID_TRANSITION M4_YY_CALL_LAST_ARG);
+
+ if ((dmap = yytbl_dmap_lookup (dmap, td.td_id M4_YY_CALL_LAST_ARG)) == NULL){
+ yy_fatal_error("table id not found in map." /*TODO: not fatal.*/ M4_YY_CALL_LAST_ARG);
+ return -1;
+ }
+
+ /* Allocate space for table.
+ * The --full yy_transition table is a special case, since we
+ * need the dmap.dm_sz entry to tell us the sizeof the individual
+ * struct members.
+ */
+ {
+ size_t bytes;
+
+ if ((td.td_flags & YYTD_STRUCT))
+ bytes = sizeof(struct yy_trans_info) * td.td_lolen * (td.td_hilen ? td.td_hilen : 1);
+ else
+ bytes = td.td_lolen * (td.td_hilen ? td.td_hilen : 1) * dmap->dm_sz;
+
+ if(M4_YY_TABLES_VERIFY)
+ /* We point to the array itself */
+ p = dmap->dm_arr;
+ else
+ /* We point to the address of a pointer. */
+ *dmap->dm_arr = p = (void *) yyalloc (bytes M4_YY_CALL_LAST_ARG);
+ if ( ! p )
+ YY_FATAL_ERROR( "out of dynamic memory in yytbl_data_load()" );
+ }
+
+ /* If it's a struct, we read 2 integers to get one element */
+ if ((td.td_flags & YYTD_STRUCT) != 0)
+ inner_loop_count = 2;
+ else
+ inner_loop_count = 1;
+
+ /* read and map each element.
+ * This loop iterates once for each element of the td_data array.
+ * Notice that we increment 'i' in the inner loop.
+ */
+ len = yytbl_calc_total_len (&td);
+ for (i = 0; i < len; ){
+ int j;
+
+
+ /* This loop really executes exactly 1 or 2 times.
+ * The second time is to handle the second member of the
+ * YYTD_STRUCT for the yy_transition array.
+ */
+ for (j = 0; j < inner_loop_count; j++, i++) {
+ flex_int32_t t32;
+
+ /* read into t32 no matter what the real size is. */
+ {
+ flex_int16_t t16;
+ flex_int8_t t8;
+
+ switch (YYTDFLAGS2BYTES (td.td_flags)) {
+ case sizeof (flex_int32_t):
+ rv = yytbl_read32 (&t32, rd);
+ break;
+ case sizeof (flex_int16_t):
+ rv = yytbl_read16 (&t16, rd);
+ t32 = t16;
+ break;
+ case sizeof (flex_int8_t):
+ rv = yytbl_read8 (&t8, rd);
+ t32 = t8;
+ break;
+ default:
+ yy_fatal_error("invalid td_flags" /*TODO: not fatal.*/ M4_YY_CALL_LAST_ARG);
+ return -1;
+ }
+ }
+ if (rv != 0)
+ return -1;
+
+ /* copy into the deserialized array... */
+
+ if ((td.td_flags & YYTD_STRUCT)) {
+ /* t32 is the j'th member of a two-element struct. */
+ void *v;
+
+ v = j == 0 ? &(((struct yy_trans_info *) p)->yy_verify)
+ : &(((struct yy_trans_info *) p)->yy_nxt);
+
+ switch (dmap->dm_sz) {
+ case sizeof (flex_int32_t):
+ if (M4_YY_TABLES_VERIFY){
+ if( ((flex_int32_t *) v)[0] != (flex_int32_t) t32)
+ yy_fatal_error("tables verification failed at YYTD_STRUCT flex_int32_t" M4_YY_CALL_LAST_ARG);
+ }else
+ ((flex_int32_t *) v)[0] = (flex_int32_t) t32;
+ break;
+ case sizeof (flex_int16_t):
+ if (M4_YY_TABLES_VERIFY ){
+ if(((flex_int16_t *) v)[0] != (flex_int16_t) t32)
+ yy_fatal_error("tables verification failed at YYTD_STRUCT flex_int16_t" M4_YY_CALL_LAST_ARG);
+ }else
+ ((flex_int16_t *) v)[0] = (flex_int16_t) t32;
+ break;
+ case sizeof(flex_int8_t):
+ if (M4_YY_TABLES_VERIFY ){
+ if( ((flex_int8_t *) v)[0] != (flex_int8_t) t32)
+ yy_fatal_error("tables verification failed at YYTD_STRUCT flex_int8_t" M4_YY_CALL_LAST_ARG);
+ }else
+ ((flex_int8_t *) v)[0] = (flex_int8_t) t32;
+ break;
+ default:
+ yy_fatal_error("invalid dmap->dm_sz for struct" /*TODO: not fatal.*/ M4_YY_CALL_LAST_ARG);
+ return -1;
+ }
+
+ /* if we're done with j, increment p */
+ if (j == 1)
+ p = (struct yy_trans_info *) p + 1;
+ }
+ else if ((td.td_flags & YYTD_PTRANS)) {
+ /* t32 is an index into the transition array. */
+ struct yy_trans_info *v;
+
+
+ if (!transdmap){
+ yy_fatal_error("transition table not found" /*TODO: not fatal.*/ M4_YY_CALL_LAST_ARG);
+ return -1;
+ }
+
+ if( M4_YY_TABLES_VERIFY)
+ v = &(((struct yy_trans_info *) (transdmap->dm_arr))[t32]);
+ else
+ v = &((*((struct yy_trans_info **) (transdmap->dm_arr)))[t32]);
+
+ if(M4_YY_TABLES_VERIFY ){
+ if( ((struct yy_trans_info **) p)[0] != v)
+ yy_fatal_error("tables verification failed at YYTD_PTRANS" M4_YY_CALL_LAST_ARG);
+ }else
+ ((struct yy_trans_info **) p)[0] = v;
+
+ /* increment p */
+ p = (struct yy_trans_info **) p + 1;
+ }
+ else {
+ /* t32 is a plain int. copy data, then incrememnt p. */
+ switch (dmap->dm_sz) {
+ case sizeof (flex_int32_t):
+ if(M4_YY_TABLES_VERIFY ){
+ if( ((flex_int32_t *) p)[0] != (flex_int32_t) t32)
+ yy_fatal_error("tables verification failed at flex_int32_t" M4_YY_CALL_LAST_ARG);
+ }else
+ ((flex_int32_t *) p)[0] = (flex_int32_t) t32;
+ p = ((flex_int32_t *) p) + 1;
+ break;
+ case sizeof (flex_int16_t):
+ if(M4_YY_TABLES_VERIFY ){
+ if( ((flex_int16_t *) p)[0] != (flex_int16_t) t32)
+ yy_fatal_error("tables verification failed at flex_int16_t" M4_YY_CALL_LAST_ARG);
+ }else
+ ((flex_int16_t *) p)[0] = (flex_int16_t) t32;
+ p = ((flex_int16_t *) p) + 1;
+ break;
+ case sizeof (flex_int8_t):
+ if(M4_YY_TABLES_VERIFY ){
+ if( ((flex_int8_t *) p)[0] != (flex_int8_t) t32)
+ yy_fatal_error("tables verification failed at flex_int8_t" M4_YY_CALL_LAST_ARG);
+ }else
+ ((flex_int8_t *) p)[0] = (flex_int8_t) t32;
+ p = ((flex_int8_t *) p) + 1;
+ break;
+ default:
+ yy_fatal_error("invalid dmap->dm_sz for plain int" /*TODO: not fatal.*/ M4_YY_CALL_LAST_ARG);
+ return -1;
+ }
+ }
+ }
+
+ }
+
+ /* Now eat padding. */
+ {
+ int pad;
+ pad = yypad64(rd->bread);
+ while(--pad >= 0){
+ flex_int8_t t8;
+ if(yytbl_read8(&t8,rd) != 0)
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+%define-yytables The name for this specific scanner's tables.
+
+/* Find the key and load the DFA tables from the given stream. */
+static int yytbl_fload YYFARGS2(FILE *, fp, const char *, key)
+{
+ int rv=0;
+ struct yytbl_hdr th;
+ struct yytbl_reader rd;
+
+ rd.fp = fp;
+ th.th_version = NULL;
+
+ /* Keep trying until we find the right set of tables or end of file. */
+ while (!feof(rd.fp)) {
+ rd.bread = 0;
+ if (yytbl_hdr_read (&th, &rd M4_YY_CALL_LAST_ARG) != 0){
+ rv = -1;
+ goto return_rv;
+ }
+
+ /* A NULL key means choose the first set of tables. */
+ if (key == NULL)
+ break;
+
+ if (strcmp(th.th_name,key) != 0){
+ /* Skip ahead to next set */
+ fseek(rd.fp, th.th_ssize - th.th_hsize, SEEK_CUR);
+ yyfree(th.th_version M4_YY_CALL_LAST_ARG);
+ th.th_version = NULL;
+ }
+ else
+ break;
+ }
+
+ while (rd.bread < th.th_ssize){
+ /* Load the data tables */
+ if(yytbl_data_load (yydmap,&rd M4_YY_CALL_LAST_ARG) != 0){
+ rv = -1;
+ goto return_rv;
+ }
+ }
+
+return_rv:
+ if(th.th_version){
+ yyfree(th.th_version M4_YY_CALL_LAST_ARG);
+ th.th_version = NULL;
+ }
+
+ return rv;
+}
+
+/** Load the DFA tables for this scanner from the given stream. */
+int yytables_fload YYFARGS1(FILE *, fp)
+{
+
+ if( yytbl_fload(fp, YYTABLES_NAME M4_YY_CALL_LAST_ARG) != 0)
+ return -1;
+ return 0;
+}
+
+/** Destroy the loaded tables, freeing memory, etc.. */
+int yytables_destroy YYFARGS0(void)
+{
+ struct yytbl_dmap *dmap=0;
+
+ if(!M4_YY_TABLES_VERIFY){
+ /* Walk the dmap, freeing the pointers */
+ for(dmap=yydmap; dmap->dm_id; dmap++) {
+ void * v;
+ v = dmap->dm_arr;
+ if(v && *(char**)v){
+ yyfree(*(char**)v M4_YY_CALL_LAST_ARG);
+ *(char**)v = NULL;
+ }
+ }
+ }
+
+ return 0;
+}
+
+/* end table serialization code definitions */
+%endif
+
+
+m4_ifdef([[M4_YY_MAIN]], [[
+int main M4_YY_PARAMS(void);
+
+int main ()
+{
+
+%if-reentrant
+ yyscan_t lexer;
+ yylex_init(&lexer);
+ yylex( lexer );
+ yylex_destroy( lexer);
+
+%endif
+%if-not-reentrant
+ yylex();
+%endif
+
+ return 0;
+}
+]])
+
+%ok-for-header
+m4_ifdef( [[M4_YY_IN_HEADER]],
+[[
+#undef YY_NEW_FILE
+#undef YY_FLUSH_BUFFER
+#undef yy_set_bol
+#undef yy_new_buffer
+#undef yy_set_interactive
+#undef YY_DO_BEFORE_ACTION
+
+#ifdef YY_DECL_IS_OURS
+#undef YY_DECL_IS_OURS
+#undef YY_DECL
+#endif
+]])
diff --git a/tools/mhmake/src/flexint.h b/tools/mhmake/src/flexint.h
new file mode 100644
index 000000000..673aa1757
--- /dev/null
+++ b/tools/mhmake/src/flexint.h
@@ -0,0 +1,63 @@
+/* flex integer type definitions */
+
+#ifndef FLEXINT_H
+#define FLEXINT_H
+
+/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
+
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+
+/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
+ * if you want the limit (max/min) macros for int types.
+ */
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS 1
+#endif
+
+#include <inttypes.h>
+typedef int8_t flex_int8_t;
+typedef uint8_t flex_uint8_t;
+typedef int16_t flex_int16_t;
+typedef uint16_t flex_uint16_t;
+typedef int32_t flex_int32_t;
+typedef uint32_t flex_uint32_t;
+#else
+typedef signed char flex_int8_t;
+typedef short int flex_int16_t;
+typedef int flex_int32_t;
+typedef unsigned char flex_uint8_t;
+typedef unsigned short int flex_uint16_t;
+typedef unsigned int flex_uint32_t;
+#endif /* ! C99 */
+
+/* Limits of integral types. */
+#ifndef INT8_MIN
+#define INT8_MIN (-128)
+#endif
+#ifndef INT16_MIN
+#define INT16_MIN (-32767-1)
+#endif
+#ifndef INT32_MIN
+#define INT32_MIN (-2147483647-1)
+#endif
+#ifndef INT8_MAX
+#define INT8_MAX (127)
+#endif
+#ifndef INT16_MAX
+#define INT16_MAX (32767)
+#endif
+#ifndef INT32_MAX
+#define INT32_MAX (2147483647)
+#endif
+#ifndef UINT8_MAX
+#define UINT8_MAX (255U)
+#endif
+#ifndef UINT16_MAX
+#define UINT16_MAX (65535U)
+#endif
+#ifndef UINT32_MAX
+#define UINT32_MAX (4294967295U)
+#endif
+
+
+#endif /* ! FLEXINT_H */
diff --git a/tools/mhmake/src/flexlexer.h b/tools/mhmake/src/flexlexer.h
new file mode 100644
index 000000000..33132dc93
--- /dev/null
+++ b/tools/mhmake/src/flexlexer.h
@@ -0,0 +1,271 @@
+// -*-C++-*-
+// FlexLexer.h -- define interfaces for lexical analyzer classes generated
+// by flex
+
+// Copyright (c) 1993 The Regents of the University of California.
+// All rights reserved.
+//
+// This code is derived from software contributed to Berkeley by
+// Kent Williams and Tom Epperly.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+
+// 1. Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+
+// Neither the name of the University nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+
+// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+// PURPOSE.
+
+// This file defines FlexLexer, an abstract class which specifies the
+// external interface provided to flex C++ lexer objects, and yyFlexLexer,
+// which defines a particular lexer class.
+//
+// If you want to create multiple lexer classes, you use the -P flag
+// to rename each yyFlexLexer to some other xxFlexLexer. You then
+// include <FlexLexer.h> in your other sources once per lexer class:
+//
+// #undef yyFlexLexer
+// #define yyFlexLexer xxFlexLexer
+// #include <FlexLexer.h>
+//
+// #undef yyFlexLexer
+// #define yyFlexLexer zzFlexLexer
+// #include <FlexLexer.h>
+// ...
+
+#ifndef __FLEX_LEXER_H
+// Never included before - need to define base class.
+#define __FLEX_LEXER_H
+class mhmakefileparser;
+
+#include "refptr.h"
+
+struct YYSTYPE
+{
+ string theString;
+ int ival;
+};
+typedef struct YYSTYPE YYSTYPE;
+
+#include "location.hh"
+
+#include <iostream>
+# ifndef FLEX_STD
+# define FLEX_STD std::
+# endif
+
+extern "C++" {
+
+struct yy_buffer_state;
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+typedef int yy_state_type;
+
+class FlexLexer {
+public:
+ FlexLexer() : m_BraceIndent(0) {}
+ virtual ~FlexLexer() { }
+
+ const char* YYText() const { return yytext; }
+ int YYLeng() const { return yyleng; }
+
+ virtual void
+ yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0;
+ virtual struct yy_buffer_state*
+ yy_create_buffer( FLEX_STD istream* s, int size ) = 0;
+ virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0;
+ virtual void yyrestart( FLEX_STD istream* s ) = 0;
+
+ virtual int yylex(YYSTYPE *yylval, yy::location* yylloc) = 0;
+
+ // Switch to new input/output streams. A nil stream pointer
+ // indicates "keep the current one".
+ virtual void switch_streams( FLEX_STD istream* new_in = 0,
+ FLEX_STD ostream* new_out = 0 ) = 0;
+
+ int debug() const { return yy_flex_debug; }
+ void set_debug( int flag ) { yy_flex_debug = flag; }
+
+protected:
+ char* yytext;
+ int yyleng;
+ int yy_flex_debug; // only has effect with -d or "%option debug"
+
+public:
+
+ struct INSTACK
+ {
+ YY_BUFFER_STATE m_BufferState;
+ ifstream m_Stream;
+ string m_FileName;
+ yy::location yylloc;
+ INSTACK(YY_BUFFER_STATE BufferState, const string &FileToOpen, const string &PrevFileName, yy::location *pLocInfo) :
+ m_BufferState(BufferState),
+ m_FileName(PrevFileName),
+ yylloc(*pLocInfo),
+ m_Stream(FileToOpen.c_str(), ios_base::in)
+ {
+ }
+ bool fail() const
+ {
+ return m_Stream.fail();
+ }
+ ifstream *GetStream()
+ {
+ return &m_Stream;
+ }
+ };
+ class mystack: public iterstack<INSTACK*>
+ {
+ public:
+ ~mystack()
+ {
+ iterator It=begin();
+ while (It!=end())
+ {
+ delete *It;
+ It++;
+ }
+ }
+ void pop()
+ {
+ INSTACK *pToRemove=top();
+ iterstack<INSTACK*>::pop();
+ delete pToRemove; /* Buffer does not need to be deleted because the lexer does this when it calls the pop */
+ }
+ };
+ int m_BraceIndent;
+ size_t m_IndentSkip;
+ iterstack<int> m_IndentStack;
+ bool m_IgnoreIncludeError;
+ string m_InputFileName;
+ string m_curtoken;
+ mystack m_IncludeStack;
+ mhmakefileparser *m_pMakefileParser;
+ mhmakefileparser *GetParser(void)
+ {
+ return m_pMakefileParser;
+ }
+public:
+ string &GetInputFilename(void)
+ {
+ return m_InputFileName;
+ }
+};
+
+}
+
+#if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce)
+// Either this is the first time through (yyFlexLexerOnce not defined),
+// or this is a repeated include to define a different flavor of
+// yyFlexLexer, as discussed in the flex manual.
+#define yyFlexLexerOnce
+
+extern "C++" {
+
+class mhmakeFlexLexer : public FlexLexer {
+public:
+ // arg_yyin and arg_yyout default to the cin and cout, but we
+ // only make that assignment when initializing in yylex().
+ mhmakeFlexLexer( FLEX_STD istream* arg_yyin = 0, FLEX_STD ostream* arg_yyout = 0 );
+
+ virtual ~mhmakeFlexLexer();
+
+ void yy_switch_to_buffer( struct yy_buffer_state* new_buffer );
+ struct yy_buffer_state* yy_create_buffer( FLEX_STD istream* s, int size );
+ void yy_delete_buffer( struct yy_buffer_state* b );
+ void yyrestart( FLEX_STD istream* s );
+
+ void yypush_buffer_state( struct yy_buffer_state* new_buffer );
+ void yypop_buffer_state();
+
+ virtual int yylex(YYSTYPE* yylval, yy::location* yylloc);
+ virtual void switch_streams( FLEX_STD istream* new_in, FLEX_STD ostream* new_out = 0 );
+
+protected:
+ virtual int LexerInput( char* buf, int max_size );
+ virtual void LexerOutput( const char* buf, int size );
+ virtual void LexerError( const char* msg );
+
+ void yyunput( int c, char* buf_ptr );
+ int yyinput();
+ int yywrap();
+
+ void yy_load_buffer_state();
+ void yy_init_buffer( struct yy_buffer_state* b, FLEX_STD istream* s );
+ void yy_flush_buffer( struct yy_buffer_state* b );
+
+ int yy_start_stack_ptr;
+ int yy_start_stack_depth;
+ int* yy_start_stack;
+
+ void yy_push_state( int new_state );
+ void yy_pop_state();
+ int yy_top_state();
+
+ yy_state_type yy_get_previous_state();
+ yy_state_type yy_try_NUL_trans( yy_state_type current_state );
+ int yy_get_next_buffer();
+
+ FLEX_STD istream* yyin; // input source for default LexerInput
+ FLEX_STD ostream* yyout; // output sink for default LexerOutput
+
+ // yy_hold_char holds the character lost when yytext is formed.
+ char yy_hold_char;
+
+ // Number of characters read into yy_ch_buf.
+ int yy_n_chars;
+
+ // Points to current character in buffer.
+ char* yy_c_buf_p;
+
+ int yy_init; // whether we need to initialize
+ int yy_start; // start state number
+
+ // Flag which is used to allow yywrap()'s to do buffer switches
+ // instead of setting up a fresh yyin. A bit of a hack ...
+ int yy_did_buffer_switch_on_eof;
+
+
+ size_t yy_buffer_stack_top; /**< index of top of stack. */
+ size_t yy_buffer_stack_max; /**< capacity of stack. */
+ struct yy_buffer_state ** yy_buffer_stack; /**< Stack as an array. */
+ void yyensure_buffer_stack(void);
+
+ // The following are not always needed, but may be depending
+ // on use of certain flex features (like REJECT or yymore()).
+
+ yy_state_type yy_last_accepting_state;
+ char* yy_last_accepting_cpos;
+
+ yy_state_type* yy_state_buf;
+ yy_state_type* yy_state_ptr;
+
+ char* yy_full_match;
+ int* yy_full_state;
+ int yy_full_lp;
+
+ int yy_lp;
+ int yy_looking_for_trail_begin;
+
+ int yy_more_flag;
+ int yy_more_len;
+ int yy_more_offset;
+ int yy_prev_more_offset;
+};
+
+}
+
+#endif // yyFlexLexer || ! yyFlexLexerOnce
+
+#endif // FLEXLEXER_H
diff --git a/tools/mhmake/src/functions.cpp b/tools/mhmake/src/functions.cpp
new file mode 100644
index 000000000..1071d2604
--- /dev/null
+++ b/tools/mhmake/src/functions.cpp
@@ -0,0 +1,983 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+
+#include "util.h"
+#include "mhmakefileparser.h"
+#include "rule.h"
+
+static const string s_QuoteString("\"");
+
+funcdef mhmakefileparser::m_FunctionsDef[]= {
+ {"filter", &mhmakefileparser::f_filter}
+ ,{"call", &mhmakefileparser::f_call}
+ ,{"subst", &mhmakefileparser::f_subst}
+ ,{"patsubst", &mhmakefileparser::f_patsubst}
+ ,{"concat", &mhmakefileparser::f_concat}
+ ,{"if", &mhmakefileparser::f_if}
+ ,{"findstring", &mhmakefileparser::f_findstring}
+ ,{"firstword", &mhmakefileparser::f_firstword}
+ ,{"wildcard", &mhmakefileparser::f_wildcard}
+ ,{"basename", &mhmakefileparser::f_basename}
+ ,{"notdir", &mhmakefileparser::f_notdir}
+ ,{"dir", &mhmakefileparser::f_dir}
+ ,{"shell", &mhmakefileparser::f_shell}
+ ,{"relpath", &mhmakefileparser::f_relpath}
+ ,{"toupper", &mhmakefileparser::f_toupper}
+ ,{"tolower", &mhmakefileparser::f_tolower}
+ ,{"exist", &mhmakefileparser::f_exist}
+ ,{"filesindirs",&mhmakefileparser::f_filesindirs}
+ ,{"fullname" ,&mhmakefileparser::f_fullname}
+ ,{"addprefix" ,&mhmakefileparser::f_addprefix}
+ ,{"addsuffix" ,&mhmakefileparser::f_addsuffix}
+ ,{"filter-out" ,&mhmakefileparser::f_filterout}
+ ,{"word" ,&mhmakefileparser::f_word}
+ ,{"words" ,&mhmakefileparser::f_words}
+ ,{"strip" ,&mhmakefileparser::f_strip}
+ ,{"which" ,&mhmakefileparser::f_which}
+ ,{"foreach" ,&mhmakefileparser::f_foreach}
+ ,{"eval" ,&mhmakefileparser::f_eval}
+ ,{"sort" ,&mhmakefileparser::f_sort}
+ ,{"error" ,&mhmakefileparser::f_error}
+ ,{"info" ,&mhmakefileparser::f_info}
+ ,{"warning" ,&mhmakefileparser::f_warning}
+};
+
+map<string,function_f> mhmakefileparser::m_Functions;
+
+bool mhmakefileparser::m_FunctionsInitialised;
+
+inline const char *NextCharExprItem(const char *pTmp,string &Output,char Char)
+{
+ const char *pStart=pTmp;
+ while (*pTmp)
+ {
+ char CurChar=*pTmp;
+ if (CurChar==Char)
+ break;
+ pTmp++;
+ if (CurChar=='$' && *pTmp!='$')
+ pTmp=SkipMakeExpr(pTmp);
+ }
+
+ const char *pStop=pTmp;
+ if (*pTmp) pTmp++;
+
+ while (pStart<pStop && (*pStart==' ' || *pStart == '\t')) pStart++;
+ pStop--;
+ while (pStart<=pStop && (*pStop==' ' || *pStop == '\t')) pStop--;
+ pStop++;
+
+ Output=string(pStart,pStop);
+ return pTmp;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Loop over a list of filenames
+static string IterList(const string &List,string (*iterFunc)(const string &FileName,void *pArg), void *pArg=NULL)
+{
+ const char *pTmp=List.c_str();
+ string Ret=g_EmptyString;
+ bool first=true;
+ while (*pTmp)
+ {
+ if (!first)
+ {
+ Ret+=g_SpaceString;
+ }
+ else
+ {
+ first=false;
+ }
+ string Item;
+ pTmp=NextItem(pTmp,Item);
+ Item=iterFunc(Item,pArg);
+ if (Item.empty())
+ first=true; // Do not add space the next iteration
+ else
+ Ret+=Item;
+ }
+
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::InitFuncs(void)
+{
+ for (int i=0; i<sizeof(m_FunctionsDef)/sizeof(funcdef); i++)
+ m_Functions[m_FunctionsDef[i].szFuncName]=m_FunctionsDef[i].pFunc;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string TrimString(const string &Input)
+{
+ unsigned Start=0;
+ const char *pInput=Input.c_str();
+ while (strchr(" \t",pInput[Start])) Start++;
+ if (Start>=Input.size())
+ return g_EmptyString;
+ size_t Stop=Input.size()-1;
+ while (strchr(" \t",pInput[Stop])) Stop--;
+ return Input.substr(Start,Stop-Start+1);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+static string filter(const string &FileName, void *pvFilter)
+{
+ string *pFilter=(string*)pvFilter;
+ if (PercentMatchList(UnquoteFileName(FileName),*pFilter))
+ return FileName;
+ else
+ return g_EmptyString;
+}
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_filter(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ size_t ipos=Arg.find(',');
+ #ifdef _DEBUG
+ if (ipos==string::npos) {
+ throw string("filter func should have 2 arguments: ")+Arg;
+ }
+ #endif
+ string Str=TrimString(Arg.substr(0,ipos));
+ string List=Arg.substr(ipos+1);
+
+ if (Str.empty())
+ return Str;
+
+ return IterList(List,filter,(void*)&Str);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_filterout(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ size_t ipos=Arg.find(',');
+ #ifdef _DEBUG
+ if (ipos==string::npos) {
+ throw string("filter func should have 2 arguments: ")+Arg;
+ }
+ #endif
+ string Str=TrimString(Arg.substr(0,ipos));
+ string List=Arg.substr(ipos+1);
+
+ if (Str.empty())
+ return Str;
+
+ bool First=true;
+ string Ret;
+ char *pTok=strtok((char*)List.c_str()," \t"); // doing this is changing string, so this is very dangerous
+ while (pTok)
+ {
+ string Item(pTok);
+ if (!PercentMatchList(Item,Str))
+ {
+ if (First)
+ {
+ Ret=Item;
+ First=false;
+ }
+ else
+ {
+ Ret+=g_SpaceString;
+ Ret+=Item;
+ }
+ }
+ pTok=strtok(NULL," \t");
+ }
+ return Ret;
+}
+
+class varstack_t : public vector< pair<bool,string> >
+{
+ mhmakefileparser *m_pMakefileParser;
+public:
+ varstack_t(mhmakefileparser *pMakefileParser)
+ : m_pMakefileParser(pMakefileParser)
+ {
+ }
+ void PushArg(int ArgNr, const string &Value)
+ {
+ char szVarName[10];
+ ::sprintf(szVarName,"%d",ArgNr);
+ string VarName(szVarName);
+ string VarVal;
+ if (m_pMakefileParser->GetVariable(VarName,VarVal))
+ vector< pair<bool,string> >::push_back(pair<bool,string>(true, VarVal));
+ else
+ vector< pair<bool,string> >::push_back(pair<bool,string>(false,g_EmptyString));
+ m_pMakefileParser->SetVariable(VarName,Value);
+ }
+ void RestoreArgs()
+ {
+ vector< pair<bool,string> >::iterator It=begin();
+ int ArgNr=0;
+ while (It!=end())
+ {
+ char szVarName[10];
+ ::sprintf(szVarName,"%d",ArgNr);
+ string VarName(szVarName);
+ if (It->first)
+ m_pMakefileParser->SetVariable(VarName, It->second);
+ else
+ {
+ m_pMakefileParser->DeleteVariable(VarName);
+ }
+ It++;
+ ArgNr++;
+ }
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_call(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ varstack_t VarStack((mhmakefileparser*)this);
+ const char *pTmp=Arg.c_str();
+
+ bool LastCharIsComma=Arg[Arg.length()-1]==',';
+
+ string Func;
+ pTmp=NextCharItem(pTmp,Func,',');
+ map<string,string>::const_iterator pFunc=m_Variables.find(Func);
+ #ifdef _DEBUG
+ if (pFunc==m_Variables.end())
+ {
+ throw string("call to non existing function ")+Func;
+ }
+ #endif
+ // the 0 argument is the function itself
+ VarStack.PushArg(0,Func);
+
+ Func=pFunc->second;
+ int i=0;
+ while (*pTmp || LastCharIsComma) {
+ if (!*pTmp)
+ LastCharIsComma=false; /* To stop the loop */
+ string Repl;
+ pTmp=NextCharItem(pTmp,Repl,',');
+ i++;
+ VarStack.PushArg(i,Repl);
+ }
+
+ string Ret=ExpandExpression(Func);
+
+ VarStack.RestoreArgs();
+
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_subst(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+
+ string FromString;
+ pTmp=NextCharItem(pTmp,FromString,',');
+ #ifdef _DEBUG
+ if (!*pTmp) {
+ throw string("Wrong number of arguments in function subst");
+ }
+ #endif
+
+ string ToString;
+ pTmp=NextCharItem(pTmp,ToString,',');
+ string Text;
+ NextCharItem(pTmp,Text,',');
+
+ if (FromString.empty())
+ return Text;
+
+ string Ret;
+ size_t Pos=Text.find(FromString);
+ size_t PrevPos=0;
+ while (Pos!=string::npos)
+ {
+ Ret+=Text.substr(PrevPos,Pos-PrevPos);
+ Ret+=ToString;
+ PrevPos=Pos+FromString.length();
+ Pos=Text.find(FromString,PrevPos);
+ }
+ Ret+=Text.substr(PrevPos);
+
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_patsubst(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+
+ string FromString;
+ pTmp=NextCharItem(pTmp,FromString,',');
+ #ifdef _DEBUG
+ if (!*pTmp) {
+ throw string("Wrong number of arguments in function subst");
+ }
+ #endif
+
+ string ToString;
+ pTmp=NextCharItem(pTmp,ToString,',');
+ string Text;
+ NextCharItem(pTmp,Text,',');
+
+ if (FromString.empty())
+ return Text;
+
+ return Substitute(Text,FromString,ToString);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_concat(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+
+ string JoinString;
+ pTmp=NextCharItem(pTmp,JoinString,',');
+
+ string List;
+ pTmp=NextCharItem(pTmp,List,',');
+
+ if (JoinString.empty() && List.empty())
+ {
+ /* assume as $(concat ,,items) construct */
+ JoinString=",";
+ pTmp=NextCharItem(pTmp,List,',');
+ }
+
+ bool First=true;
+ string Ret;
+ char *pTok=strtok((char*)List.c_str()," \t"); // doing this is changing string, so this is very dangerous
+ while (pTok)
+ {
+ if (First)
+ {
+ First=false;
+ }
+ else
+ {
+ Ret+=JoinString;
+ }
+ Ret+=pTok;
+ pTok=strtok(NULL," \t");
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Make sure to only expand the expression which the condition is true for
+string mhmakefileparser::f_if(const string & Arg) const
+{
+ const char *pTmp=Arg.c_str();
+
+ string Cond;
+ pTmp=NextCharExprItem(pTmp,Cond,',');
+ Cond=ExpandExpression(Cond);
+ string Ret;
+ if (Cond.empty())
+ {
+ pTmp=NextCharExprItem(pTmp,Ret,',');
+ }
+ NextCharExprItem(pTmp,Ret,',');
+ return ExpandExpression(Ret);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_findstring(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+ string find;
+ pTmp=NextCharItem(pTmp,find,',');
+ string instr;
+ NextCharItem(pTmp,instr,',');
+
+ if (instr.find(find) != instr.npos)
+ return find;
+ else
+ return g_EmptyString;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_firstword(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ string FirstWord;
+ NextItem(Arg.c_str(),FirstWord);
+ return FirstWord;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string wildcard(const string &Arg, void *pvVar)
+{
+ mhmakefileparser *pParser=(mhmakefileparser*)pvVar;
+
+ fileinfo *pFileSpec=GetFileInfo(Arg,pParser->GetMakeDir()); /* Use GetFileInfo to make the relative path absolute */
+ fileinfo *pDir=pFileSpec->GetDir();
+#ifdef WIN32
+ struct _finddata_t FileInfo;
+ intptr_t hFile=_findfirst(pFileSpec->GetFullFileName().c_str(),&FileInfo);
+ if (hFile==-1)
+ return g_EmptyString;
+
+ string Ret=g_EmptyString;
+
+ /* We have to verify with percentmatch since the find functions *.ext also matches the functions *.extbrol */
+ string CheckSpec=pFileSpec->GetName();
+ if (PercentMatchNoCase(FileInfo.name,CheckSpec,NULL,'*'))
+ {
+ Ret=GetFileInfo(FileInfo.name,pDir)->GetQuotedFullFileName();
+ }
+ while (-1!=_findnext(hFile,&FileInfo))
+ {
+ if (PercentMatchNoCase(FileInfo.name,CheckSpec,NULL,'*'))
+ {
+ Ret+=g_SpaceString;
+ Ret+=GetFileInfo(FileInfo.name,pDir)->GetQuotedFullFileName();
+ }
+ }
+ _findclose(hFile);
+#else
+ glob_t Res;
+ if (glob (pFileSpec->GetFullFileName().c_str(), GLOB_ERR|GLOB_NOSORT|GLOB_MARK, NULL, &Res))
+ return g_EmptyString;
+
+ string Ret=g_EmptyString;
+ string SepStr=g_EmptyString;
+ string CheckSpec=pFileSpec->GetName();
+ for (int i=0; i<Res.gl_pathc; i++)
+ {
+ if (PercentMatch(Res.gl_pathv[i],CheckSpec,NULL,'*'))
+ {
+ Ret+=SepStr;
+ Ret+=GetFileInfo(Res.gl_pathv[i],pDir)->GetQuotedFullFileName();
+ SepStr=g_SpaceString;
+ }
+ }
+
+ globfree(&Res);
+#endif
+ return Ret;
+}
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_wildcard(const string & Arg) const
+{
+ return IterList(ExpandExpression(Arg), wildcard, (void*)this);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_exist(const string & Arg) const
+{
+ string File=TrimString(ExpandExpression(Arg));
+ fileinfo *pFile=GetFileInfo(File,m_MakeDir);
+ if (pFile->Exists())
+ {
+ return string("1");
+ }
+ else
+ return g_EmptyString;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_filesindirs(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+
+ string strFiles;
+ pTmp=NextCharItem(pTmp,strFiles,',');
+ #ifdef _DEBUG
+ if (!*pTmp) {
+ throw string("Wrong number of arguments in function filesindirs");
+ }
+ #endif
+ string strDirs;
+ NextCharItem(pTmp,strDirs,',');
+
+ vector<fileinfo*> Dirs;
+ SplitToItems(strDirs,Dirs);
+
+ pTmp=strFiles.c_str();
+ string Ret=g_EmptyString;
+ bool first=true;
+ while (*pTmp)
+ {
+ string File;
+ fileinfo *pFile;
+ pTmp=NextItem(pTmp,File);
+
+ vector<fileinfo*>::iterator It=Dirs.begin();
+ vector<fileinfo*>::iterator ItEnd=Dirs.end();
+ while (It!=ItEnd)
+ {
+ pFile=GetFileInfo(File,*It++);
+ if (pFile->Exists())
+ {
+ break;
+ }
+ pFile=NULL;
+ }
+ if (!pFile)
+ continue;
+
+ if (!first)
+ {
+ Ret+=g_SpaceString;
+ }
+ else
+ {
+ first=false;
+ }
+ Ret+=pFile->GetQuotedFullFileName();
+ }
+
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_fullname(const string & Arg) const
+{
+ string File=TrimString(ExpandExpression(Arg));
+ fileinfo *pFile=GetFileInfo(File,m_MakeDir);
+ return pFile->GetQuotedFullFileName();
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string basename(const string &FileName,void*)
+{
+ string Ret=UnquoteFileName(FileName);
+ Ret=Ret.substr(0,Ret.find_last_of('.'));
+ return QuoteFileName(Ret);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_basename(const string & FileNames) const
+{
+ return IterList(ExpandExpression(FileNames),basename);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string notdir(const string &FileName,void*)
+{
+ string Ret=UnquoteFileName(FileName);
+ size_t Pos=Ret.find_last_of(OSPATHSEP);
+ if (Pos==string::npos)
+ {
+ return FileName;
+ }
+ else
+ {
+ Ret=Ret.substr(Pos+1);
+ return QuoteFileName(Ret);
+ }
+
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_notdir(const string & FileNames) const
+{
+ return IterList(ExpandExpression(FileNames),notdir);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string addprefix(const string &FileName,void *pPrefix)
+{
+ return *(const string *)pPrefix+FileName;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_addprefix(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+ string PreFix;
+ pTmp=NextCharItem(pTmp,PreFix,',');
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo && PreFix.empty()) {
+ cout << "Warning: empty prefix in expression: " << ArgIn << endl;
+ }
+ #endif
+ string FileNames;
+ pTmp=NextCharItem(pTmp,FileNames,',');
+ return IterList(FileNames,addprefix,&PreFix);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string addsuffix(const string &FileName,void *pSuffix)
+{
+ return FileName+*(const string *)pSuffix;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_addsuffix(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+ string SufFix;
+ pTmp=NextCharItem(pTmp,SufFix,',');
+ #ifdef _DEBUG
+ if (!*pTmp) {
+ throw string("Wrong number of arguments in function addsuffix");
+ }
+ #endif
+ string FileNames;
+ pTmp=NextCharItem(pTmp,FileNames,',');
+ return IterList(FileNames,addsuffix,&SufFix);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Returns the n-th word number
+string mhmakefileparser::f_word(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+
+ string strNum;
+ pTmp=NextCharItem(pTmp,strNum,',');
+
+ int WordNbr=atoi(strNum.c_str());
+
+ #ifdef _DEBUG
+ if (!WordNbr)
+ {
+ if (!WordNbr) {
+ throw string ("Expecting a number bigger then 0 for the word function");
+ }
+ }
+ #endif
+
+ int CurWord=0;
+ while (*pTmp)
+ {
+ string Word;
+ pTmp=NextItem(pTmp,Word);
+ CurWord++;
+ if (CurWord==WordNbr)
+ return Word;
+ }
+
+ return g_EmptyString;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Returns the number of words
+string mhmakefileparser::f_words(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ const char *pTmp=Arg.c_str();
+ int NrWords=0;
+ char szNumber[10];
+ while (*pTmp)
+ {
+ string Word;
+ pTmp=NextItem(pTmp,Word);
+ NrWords++;
+ }
+ sprintf(szNumber,"%d",NrWords);
+
+ return szNumber;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Search for a command in the enivornment path
+string mhmakefileparser::f_which(const string & Arg) const
+{
+ return SearchCommand(ExpandExpression(Arg));
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Removes leading and trailing space
+string mhmakefileparser::f_strip(const string & ArgIn) const
+{
+ string Arg=ExpandExpression(ArgIn);
+ string::const_iterator pFirst=Arg.begin();
+ string::const_iterator pLast=Arg.end();
+ while (strchr(" \t\r\n",*pFirst) && pFirst!=pLast) pFirst++;
+ if (pFirst==pLast)
+ return "";
+ while (strchr(" \t\r\n",*(--pLast)));
+ pLast++;
+ return Arg.substr(pFirst-Arg.begin(),pLast-pFirst);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string dir(const string &FileName, void *)
+{
+ size_t Pos=FileName.find_last_of(OSPATHSEP);
+ if (Pos==string::npos)
+ {
+ #ifdef _WIN32
+ Pos=FileName.find_last_of('/');
+ if (Pos==string::npos)
+ #endif
+ return g_EmptyString;
+ }
+
+ string Ret=g_EmptyString;
+ Ret+=FileName.substr(0,Pos+1);
+ if (FileName[0]=='"' && FileName.end()[-1]=='"')
+ Ret+=s_QuoteString;
+ return Ret;
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_dir(const string & FileNames) const
+{
+ return IterList(ExpandExpression(FileNames),dir);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_shell(const string & CommandIn) const
+{
+ string Command=ExpandExpression(CommandIn);
+ string Output;
+
+#ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "shell: executing: Command '"<<Command<<"'"<<endl;
+#endif
+
+ ((mhmakefileparser*)this)->ExecuteCommand(string("@")+Command,&Output); // Make sure that the command is not echoed
+#ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "shell returned '"<<Output<<"'"<<endl;
+#endif
+ return Output;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string relpath(const string &FileName,void *pvDir)
+{
+ const fileinfo *pDir=*(const fileinfo **)pvDir;
+ const fileinfo *pPath=GetFileInfo(FileName,pDir);
+ const char *pCur=pDir->GetFullFileName().c_str();
+ const char *pszPath=pPath->GetFullFileName().c_str();
+
+ const char *pLast=pszPath;
+ while (*pCur==*pszPath)
+ {
+ char Char=*pszPath;
+ if (!Char)
+ {
+ return "."; // Means that FileName is the same as the current directory
+ }
+ if (Char==OSPATHSEP)
+ pLast=pszPath+1;
+ pCur++;
+ pszPath++;
+ }
+ if (*pszPath==OSPATHSEP && !*pCur)
+ pLast=pszPath+1;
+ string retPath;
+ if (*pCur==OSPATHSEP) {
+ bool first=true;
+ pCur++;
+ retPath="..";
+ while (*pCur)
+ {
+ if (*pCur==OSPATHSEP)
+ retPath+=OSPATHSEPSTR"..";
+ pCur++;
+ }
+ if (pszPath)
+ retPath=retPath+OSPATHSEPSTR+pLast;
+ }
+ else
+ {
+ if (*pCur)
+ retPath=".."OSPATHSEPSTR;
+ while (*pCur)
+ {
+ if (*pCur==OSPATHSEP)
+ retPath+=".."OSPATHSEPSTR;
+ pCur++;
+ }
+ retPath+=pLast;
+ }
+ return QuoteFileName(retPath);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Make a path name relative to the current directory
+string mhmakefileparser::f_relpath(const string & FileNames) const
+{
+ return IterList(ExpandExpression(FileNames),relpath,(void*)&m_MakeDir);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string makeupper(const string &FileName,void *)
+{
+ string Ret=FileName;
+ string::const_iterator pSrc=FileName.begin();
+ string::iterator pDest=Ret.begin();
+ while (pSrc!=FileName.end())
+ {
+ *pDest++ = toupper(*pSrc++);
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_toupper(const string & FileNames) const
+{
+ return IterList(ExpandExpression(FileNames),makeupper);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string makelower(const string &FileName, void *)
+{
+ string Ret=FileName;
+ string::const_iterator pSrc=FileName.begin();
+ string::iterator pDest=Ret.begin();
+ while (pSrc!=FileName.end())
+ {
+ *pDest++ = tolower(*pSrc++);
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_tolower(const string & FileNames) const
+{
+ return IterList(ExpandExpression(FileNames),makelower);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+struct expanedexpr_arg
+{
+ string Var;
+ mhmakefileparser *pParser;
+ string Expr;
+};
+
+static string expandexpr(const string &VarVal, void *pvVar)
+{
+ expanedexpr_arg *pArg=(expanedexpr_arg*)pvVar;
+ pArg->pParser->SetVariable(pArg->Var,VarVal);
+ return pArg->pParser->ExpandExpression(pArg->Expr);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_foreach(const string & Arg) const
+{
+ const char *pTmp=Arg.c_str();
+
+ expanedexpr_arg Args;
+ Args.pParser=(mhmakefileparser*)this;
+ pTmp=NextCharExprItem(pTmp,Args.Var,',');
+ Args.Var=ExpandExpression(Args.Var);
+
+ if (Args.Var.empty())
+ throw(string("Wrong syntax in foreach instruction: '")+Arg+"'. Variable may not be empty.");
+
+ string Items;
+ pTmp=NextCharExprItem(pTmp,Items,',');
+ Items=ExpandExpression(Items);
+
+ if (Items.empty())
+ return g_EmptyString; /* No items specified, so nothing needs to be done */
+
+ pTmp=NextCharExprItem(pTmp,Args.Expr,',');
+
+ /* Save the variable to be able to restore it after the foreach expansion */
+ string VarVal;
+ map<string,string>::const_iterator pVal=m_Variables.find(Args.Var);
+ if (pVal!=m_Variables.end())
+ VarVal=pVal->second;
+
+ string Ret=IterList(Items,expandexpr,(void*)&Args);
+
+ /* Restore the variable to it's original value */
+ if (pVal!=m_Variables.end())
+ Args.pParser->SetVariable(Args.Var,VarVal);
+ else
+ Args.pParser->DeleteVariable(Args.Var);
+
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_eval(const string & Arg) const
+{
+ ((mhmakefileparser*)this)->ParseString(ExpandExpression(Arg)+"\n");
+ return g_EmptyString;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static string AddToList(const string &String, void *pvList)
+{
+ vector<string> *pList=(vector<string>*)pvList;
+ pList->push_back(String);
+ return g_EmptyString;
+}
+
+string mhmakefileparser::f_sort(const string & Arg) const
+{
+ string ExpandedArg=ExpandExpression(Arg);
+ vector<string> List;
+ IterList(ExpandedArg, AddToList, (void*)&List);
+ sort(List.begin(),List.end());
+ string Prev;
+ vector<string>::iterator It=List.begin();
+ string Ret;
+ bool First=true;
+ while (It!=List.end())
+ {
+ string This=*It++;
+ if (This!=Prev)
+ {
+ Prev=This;
+ if (!First)
+ Ret+=" ";
+ else
+ First=false;
+ Ret+=This;
+ }
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_error(const string & Arg) const
+{
+ throw(GetFileNameLineNo()+ExpandExpression(Arg));
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_warning(const string & Arg) const
+{
+ cout << GetFileNameLineNo() << ExpandExpression(Arg) << endl;
+ return g_EmptyString;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::f_info(const string & Arg) const
+{
+ cout << ExpandExpression(Arg) << endl;
+ return g_EmptyString;
+}
+
diff --git a/tools/mhmake/src/md5.cpp b/tools/mhmake/src/md5.cpp
new file mode 100644
index 000000000..df3a006cb
--- /dev/null
+++ b/tools/mhmake/src/md5.cpp
@@ -0,0 +1,455 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+/*
+ * RFC 1321 compliant MD5 implementation
+ *
+ * Copyright (C) 2001-2003 Christophe Devine
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "stdafx.h"
+#include "md5.h"
+
+#ifdef _MSC_VER
+#pragma warning (disable:4005) /* macro redefinition */
+#endif
+
+#ifdef _DEBUG
+map<uint32,string> g_Md5Database;
+#endif
+
+#define GET_UINT32(n,b,i) \
+{ \
+ (n) = ( (uint32) (b)[(i) ] ) \
+ | ( (uint32) (b)[(i) + 1] << 8 ) \
+ | ( (uint32) (b)[(i) + 2] << 16 ) \
+ | ( (uint32) (b)[(i) + 3] << 24 ); \
+}
+
+#define PUT_UINT32(n,b,i) \
+{ \
+ (b)[(i) ] = (uint8) ( (n) ); \
+ (b)[(i) + 1] = (uint8) ( (n) >> 8 ); \
+ (b)[(i) + 2] = (uint8) ( (n) >> 16 ); \
+ (b)[(i) + 3] = (uint8) ( (n) >> 24 ); \
+}
+
+void md5_starts( md5_context *ctx )
+{
+ ctx->total[0] = 0;
+ ctx->total[1] = 0;
+
+ ctx->state[0] = 0x67452301;
+ ctx->state[1] = 0xEFCDAB89;
+ ctx->state[2] = 0x98BADCFE;
+ ctx->state[3] = 0x10325476;
+#ifdef _DEBUG
+ if (g_BuildMd5Db) ctx->Data="";
+#endif
+}
+
+void md5_process( md5_context *ctx, uint8 data[64] )
+{
+ uint32 X[16], A, B, C, D;
+
+ GET_UINT32( X[0], data, 0 );
+ GET_UINT32( X[1], data, 4 );
+ GET_UINT32( X[2], data, 8 );
+ GET_UINT32( X[3], data, 12 );
+ GET_UINT32( X[4], data, 16 );
+ GET_UINT32( X[5], data, 20 );
+ GET_UINT32( X[6], data, 24 );
+ GET_UINT32( X[7], data, 28 );
+ GET_UINT32( X[8], data, 32 );
+ GET_UINT32( X[9], data, 36 );
+ GET_UINT32( X[10], data, 40 );
+ GET_UINT32( X[11], data, 44 );
+ GET_UINT32( X[12], data, 48 );
+ GET_UINT32( X[13], data, 52 );
+ GET_UINT32( X[14], data, 56 );
+ GET_UINT32( X[15], data, 60 );
+
+#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
+
+#define P(a,b,c,d,k,s,t) \
+{ \
+ a += F(b,c,d) + X[k] + t; a = S(a,s) + b; \
+}
+
+ A = ctx->state[0];
+ B = ctx->state[1];
+ C = ctx->state[2];
+ D = ctx->state[3];
+
+#define F(x,y,z) (z ^ (x & (y ^ z)))
+
+ P( A, B, C, D, 0, 7, 0xD76AA478 );
+ P( D, A, B, C, 1, 12, 0xE8C7B756 );
+ P( C, D, A, B, 2, 17, 0x242070DB );
+ P( B, C, D, A, 3, 22, 0xC1BDCEEE );
+ P( A, B, C, D, 4, 7, 0xF57C0FAF );
+ P( D, A, B, C, 5, 12, 0x4787C62A );
+ P( C, D, A, B, 6, 17, 0xA8304613 );
+ P( B, C, D, A, 7, 22, 0xFD469501 );
+ P( A, B, C, D, 8, 7, 0x698098D8 );
+ P( D, A, B, C, 9, 12, 0x8B44F7AF );
+ P( C, D, A, B, 10, 17, 0xFFFF5BB1 );
+ P( B, C, D, A, 11, 22, 0x895CD7BE );
+ P( A, B, C, D, 12, 7, 0x6B901122 );
+ P( D, A, B, C, 13, 12, 0xFD987193 );
+ P( C, D, A, B, 14, 17, 0xA679438E );
+ P( B, C, D, A, 15, 22, 0x49B40821 );
+
+#undef F
+
+#define F(x,y,z) (y ^ (z & (x ^ y)))
+
+ P( A, B, C, D, 1, 5, 0xF61E2562 );
+ P( D, A, B, C, 6, 9, 0xC040B340 );
+ P( C, D, A, B, 11, 14, 0x265E5A51 );
+ P( B, C, D, A, 0, 20, 0xE9B6C7AA );
+ P( A, B, C, D, 5, 5, 0xD62F105D );
+ P( D, A, B, C, 10, 9, 0x02441453 );
+ P( C, D, A, B, 15, 14, 0xD8A1E681 );
+ P( B, C, D, A, 4, 20, 0xE7D3FBC8 );
+ P( A, B, C, D, 9, 5, 0x21E1CDE6 );
+ P( D, A, B, C, 14, 9, 0xC33707D6 );
+ P( C, D, A, B, 3, 14, 0xF4D50D87 );
+ P( B, C, D, A, 8, 20, 0x455A14ED );
+ P( A, B, C, D, 13, 5, 0xA9E3E905 );
+ P( D, A, B, C, 2, 9, 0xFCEFA3F8 );
+ P( C, D, A, B, 7, 14, 0x676F02D9 );
+ P( B, C, D, A, 12, 20, 0x8D2A4C8A );
+
+#undef F
+
+#define F(x,y,z) (x ^ y ^ z)
+
+ P( A, B, C, D, 5, 4, 0xFFFA3942 );
+ P( D, A, B, C, 8, 11, 0x8771F681 );
+ P( C, D, A, B, 11, 16, 0x6D9D6122 );
+ P( B, C, D, A, 14, 23, 0xFDE5380C );
+ P( A, B, C, D, 1, 4, 0xA4BEEA44 );
+ P( D, A, B, C, 4, 11, 0x4BDECFA9 );
+ P( C, D, A, B, 7, 16, 0xF6BB4B60 );
+ P( B, C, D, A, 10, 23, 0xBEBFBC70 );
+ P( A, B, C, D, 13, 4, 0x289B7EC6 );
+ P( D, A, B, C, 0, 11, 0xEAA127FA );
+ P( C, D, A, B, 3, 16, 0xD4EF3085 );
+ P( B, C, D, A, 6, 23, 0x04881D05 );
+ P( A, B, C, D, 9, 4, 0xD9D4D039 );
+ P( D, A, B, C, 12, 11, 0xE6DB99E5 );
+ P( C, D, A, B, 15, 16, 0x1FA27CF8 );
+ P( B, C, D, A, 2, 23, 0xC4AC5665 );
+
+#undef F
+
+#define F(x,y,z) (y ^ (x | ~z))
+
+ P( A, B, C, D, 0, 6, 0xF4292244 );
+ P( D, A, B, C, 7, 10, 0x432AFF97 );
+ P( C, D, A, B, 14, 15, 0xAB9423A7 );
+ P( B, C, D, A, 5, 21, 0xFC93A039 );
+ P( A, B, C, D, 12, 6, 0x655B59C3 );
+ P( D, A, B, C, 3, 10, 0x8F0CCC92 );
+ P( C, D, A, B, 10, 15, 0xFFEFF47D );
+ P( B, C, D, A, 1, 21, 0x85845DD1 );
+ P( A, B, C, D, 8, 6, 0x6FA87E4F );
+ P( D, A, B, C, 15, 10, 0xFE2CE6E0 );
+ P( C, D, A, B, 6, 15, 0xA3014314 );
+ P( B, C, D, A, 13, 21, 0x4E0811A1 );
+ P( A, B, C, D, 4, 6, 0xF7537E82 );
+ P( D, A, B, C, 11, 10, 0xBD3AF235 );
+ P( C, D, A, B, 2, 15, 0x2AD7D2BB );
+ P( B, C, D, A, 9, 21, 0xEB86D391 );
+
+#undef F
+
+ ctx->state[0] += A;
+ ctx->state[1] += B;
+ ctx->state[2] += C;
+ ctx->state[3] += D;
+}
+
+static uint8 md5_padding[64] =
+{
+ 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+void md5_update( md5_context *ctx, uint8 *input, size_t length )
+{
+ uint32 left, fill;
+
+ if( ! length ) return;
+
+#ifdef _DEBUG
+ if (g_BuildMd5Db && md5_padding!=input && ctx->msglen!=input)
+ ctx->Data+=string((char*)input,length);
+#endif
+
+ left = ctx->total[0] & 0x3F;
+ fill = 64 - left;
+
+ ctx->total[0] = (uint32)((ctx->total[0] + length)& 0xFFFFFFFF);
+
+ if( ctx->total[0] < length )
+ ctx->total[1]++;
+
+ if( left && length >= fill )
+ {
+ memcpy( (void *) (ctx->buffer + left),
+ (void *) input, fill );
+ md5_process( ctx, ctx->buffer );
+ length -= fill;
+ input += fill;
+ left = 0;
+ }
+
+ while( length >= 64 )
+ {
+ md5_process( ctx, input );
+ length -= 64;
+ input += 64;
+ }
+
+ if( length )
+ {
+ memcpy( (void *) (ctx->buffer + left),
+ (void *) input, length );
+ }
+}
+
+uint32 *md5_finishbin( md5_context *ctx)
+{
+ uint32 last, padn;
+ uint32 high, low;
+
+ high = ( ctx->total[0] >> 29 )
+ | ( ctx->total[1] << 3 );
+ low = ( ctx->total[0] << 3 );
+
+ PUT_UINT32( low, ctx->msglen, 0 );
+ PUT_UINT32( high, ctx->msglen, 4 );
+
+ last = ctx->total[0] & 0x3F;
+ padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
+
+ md5_update( ctx, md5_padding, padn );
+ md5_update( ctx, ctx->msglen, 8 );
+
+ return ctx->state;
+}
+
+void md5_finish( md5_context *ctx, uint8 digest[16] )
+{
+ md5_finishbin( ctx);
+ PUT_UINT32( ctx->state[0], digest, 0 );
+ PUT_UINT32( ctx->state[1], digest, 4 );
+ PUT_UINT32( ctx->state[2], digest, 8 );
+ PUT_UINT32( ctx->state[3], digest, 12 );
+}
+
+uint32 md5_finish32( md5_context *ctx)
+{
+ md5_finishbin( ctx);
+ uint32 Md5_32=ctx->state[0]+ctx->state[1]+ctx->state[2]+ctx->state[3];
+#ifdef _DEBUG
+ if (g_BuildMd5Db) g_Md5Database[Md5_32]=ctx->Data;
+#endif
+ return Md5_32;
+}
+
+#ifdef _DEBUG
+struct WRITEMD5DB
+{
+ ~WRITEMD5DB()
+ {
+ if (g_BuildMd5Db)
+ {
+ FILE *pFile=fopen("Md5.database","wb");
+ map<uint32,string>::const_iterator It=g_Md5Database.begin();
+ while (It!=g_Md5Database.end())
+ {
+ fprintf(pFile,"%08lx: ",It->first);
+ fwrite(It->second.c_str(),It->second.length(),1,pFile);
+ fprintf(pFile,"\n");
+ It++;
+ }
+ fclose(pFile);
+ }
+ }
+};
+static WRITEMD5DB WriteMd5Db;
+#endif
+
+
+#ifdef TEST
+
+#include <stdlib.h>
+#include <stdio.h>
+
+/*
+ * those are the standard RFC 1321 test vectors
+ */
+
+static char *msg[] =
+{
+ "",
+ "a",
+ "abc",
+ "message digest",
+ "abcdefghijklmnopqrstuvwxyz",
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ "12345678901234567890123456789012345678901234567890123456789012" \
+ "345678901234567890"
+};
+
+static char *val[] =
+{
+ "d41d8cd98f00b204e9800998ecf8427e",
+ "0cc175b9c0f1b6a831c399e269772661",
+ "900150983cd24fb0d6963f7d28e17f72",
+ "f96b697d7cb7938d525a2f31aaf161d0",
+ "c3fcd3d76192e4007dfb496cca67e13b",
+ "d174ab98d277d9f5a5611c2c9f419d9f",
+ "57edf4a22be3c955ac49da2e2107b67a"
+};
+
+int main( int argc, char *argv[] )
+{
+ FILE *f;
+ int i, j;
+ char output[33];
+ md5_context ctx;
+ unsigned char buf[1000];
+ unsigned char md5sum[16];
+
+ if( argc < 2 )
+ {
+ printf( "\n MD5 Validation Tests:\n\n" );
+
+ for( i = 0; i < 7; i++ )
+ {
+ printf( " Test %d ", i + 1 );
+
+ md5_starts( &ctx );
+ md5_update( &ctx, (uint8 *) msg[i], strlen( msg[i] ) );
+ md5_finish( &ctx, md5sum );
+
+ for( j = 0; j < 16; j++ )
+ {
+ sprintf( output + j * 2, "%02x", md5sum[j] );
+ }
+
+ if( memcmp( output, val[i], 32 ) )
+ {
+ printf( "failed!\n" );
+ return( 1 );
+ }
+
+ printf( "passed.\n" );
+ }
+
+ printf( "\n" );
+ }
+ else
+ {
+ if( ! ( f = fopen( argv[1], "rb" ) ) )
+ {
+ perror( "fopen" );
+ return( 1 );
+ }
+
+ md5_starts( &ctx );
+
+ while( ( i = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
+ {
+ md5_update( &ctx, buf, i );
+ }
+
+ md5_finish( &ctx, md5sum );
+
+ for( j = 0; j < 16; j++ )
+ {
+ printf( "%02x", md5sum[j] );
+ }
+
+ printf( " %s\n", argv[1] );
+ }
+
+ return( 0 );
+}
+
+#endif
+
+//#define APP
+#ifdef APP
+#include <stdio.h>
+
+int main( int argc, char *argv[] )
+{
+ unsigned j;
+ unsigned char md5sum[16];
+ md5_context ctx;
+ FILE *pFile=fopen(argv[1],"r");
+
+ if (!pFile)
+ {
+ printf("Error opening file.\n");
+ return 1;
+ }
+
+ md5_starts( &ctx );
+
+ while (1)
+ {
+ char Buf[1024];
+ size_t Ret=fread(Buf,1,sizeof(Buf),pFile);
+ if (!Ret)
+ break;
+ md5_update( &ctx, (uint8 *) Buf, Ret);
+ }
+ md5_finish( &ctx, md5sum );
+
+ for( j = 0; j < 16; j++ )
+ {
+ printf("%02x", md5sum[j] );
+ }
+
+}
+#endif
+
diff --git a/tools/mhmake/src/md5.h b/tools/mhmake/src/md5.h
new file mode 100644
index 000000000..f16c9bd19
--- /dev/null
+++ b/tools/mhmake/src/md5.h
@@ -0,0 +1,58 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef _MD5_H
+#define _MD5_H
+
+#ifndef uint8
+#define uint8 unsigned char
+#endif
+
+#ifndef uint32
+#define uint32 unsigned long int
+#endif
+
+typedef struct
+{
+ uint32 total[2];
+ uint32 state[4];
+ uint8 buffer[64];
+ uint8 msglen[8];
+#ifdef _DEBUG
+ string Data;
+#endif
+}
+md5_context;
+
+typedef uint32 md5_val[4];
+
+void md5_starts( md5_context *ctx );
+void md5_update( md5_context *ctx, uint8 *input, size_t length );
+void md5_finish( md5_context *ctx, uint8 digest[16] );
+uint32 *md5_finishbin( md5_context *ctx);
+uint32 md5_finish32( md5_context *ctx);
+
+#ifdef _DEBUG
+extern bool g_BuildMd5Db;
+#endif
+
+#endif /* md5.h */
+
+
diff --git a/tools/mhmake/src/mhmake.cpp b/tools/mhmake/src/mhmake.cpp
new file mode 100644
index 000000000..ef515b0b2
--- /dev/null
+++ b/tools/mhmake/src/mhmake.cpp
@@ -0,0 +1,158 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+#include "fileinfo.h"
+#include "mhmakefileparser.h"
+#include "rule.h"
+#include "util.h"
+
+bool g_Clean=false;
+bool g_StopCompiling=false;
+
+#ifdef WIN32
+BOOL WINAPI ControlCHandler(DWORD dwCtrlType)
+{
+ g_StopCompiling=true;
+ return TRUE;
+}
+#endif
+
+int __CDECL main(int argc, char* argv[])
+{
+ //__int64 Freq;
+ //__int64 Start;
+
+ //QueryPerformanceFrequency((LARGE_INTEGER*)&Freq);
+ //QueryPerformanceCounter((LARGE_INTEGER*)&Start);
+
+ #if defined(_DEBUG) && defined(_MSC_VER)
+ int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
+
+ // Turn on leak-checking bit
+ tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
+ // Turn on defer freeing
+ //tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
+ // Turn on heap checking
+ //tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
+
+ // Set flag to the new value
+ _CrtSetDbgFlag( tmpFlag );
+
+ //_CrtSetBreakAlloc(44);
+ #endif
+
+ #ifdef WIN32
+ /* Remove the VS_UNICODE_OUTPUT environment variable. This variable is set when running from
+ * the Visual Studio IDE and is causing the output of cl.exe to send the output directly to the IDE instead
+ * of sending it to stdout. This is causing all scripts that are calling cl.exe and intercept the
+ * output to fail.
+ */
+ putenv("VS_UNICODE_OUTPUT=");
+
+ SetConsoleCtrlHandler(ControlCHandler, TRUE);
+
+ #endif
+
+ try
+ {
+ mhmakefileparser::InitBuildTime();
+
+ char PlatformEnv[]="PLATFORM="PLATFORM;
+ putenv(PlatformEnv);
+
+ vector<string> CmdLineArgs;
+ for (int i=1; i<argc; i++)
+ {
+ CmdLineArgs.push_back(argv[i]);
+ }
+
+ refptr<loadedmakefile> pFirstMakefile(new loadedmakefile(curdir::GetCurDir(),CmdLineArgs,"makefile"));
+ // For the first makefile we add the defines passed on the command line to the
+ // environment so that the other load_makefile see the same variables
+ pFirstMakefile->AddCommandLineVarsToEnvironment();
+
+ g_LoadedMakefiles.push_back(pFirstMakefile);
+
+ pFirstMakefile->LoadMakefile();
+
+ #ifdef _DEBUG
+ if (g_PrintVarsAndRules)
+ {
+ DumpVarsAndRules();
+ }
+ #endif
+
+ // Make sure that the included makefiles that have rules are build
+
+ LOADEDMAKEFILES::iterator LoadMakIt=g_LoadedMakefiles.begin();
+ while (LoadMakIt!=g_LoadedMakefiles.end())
+ {
+ (*LoadMakIt)->m_pMakefileParser->BuildIncludedMakefiles();
+ (*LoadMakIt)->m_pMakefileParser->ParseBuildedIncludeFiles();
+ (*LoadMakIt)->m_pMakefileParser->CheckEnv();
+ LoadMakIt++;
+ }
+
+ if (pFirstMakefile->m_CommandLineTargets.size())
+ {
+ vector<string>::iterator It=pFirstMakefile->m_CommandLineTargets.begin();
+ while (It!=pFirstMakefile->m_CommandLineTargets.end())
+ {
+ if (*It=="clean" || *It=="cleanall")
+ {
+ g_Clean=true;
+ }
+ fileinfo *pTarget=GetFileInfo(*It,pFirstMakefile->m_MakeDir);
+ pFirstMakefile->m_pMakefileParser->BuildTarget(pTarget);
+ It++;
+ }
+ }
+ else
+ {
+ fileinfo *pFirstTarget=pFirstMakefile->m_pMakefileParser->GetFirstTarget();
+ if (pFirstTarget)
+ {
+ pFirstMakefile->m_pMakefileParser->BuildTarget(pFirstTarget);
+ }
+ else
+ cout << "Warning: no targets in makefile. Nothing to be build.\nMHMAKECONF defined?\n";
+ }
+
+ }
+ catch (string Message)
+ {
+ cerr << "*** Error -> " << Message << endl;
+ #ifdef _DEBUG
+ if (g_DumpOnError)
+ {
+ DumpVarsAndRules();
+ }
+ #endif
+ return 1;
+ }
+
+ //__int64 Stop;
+ //QueryPerformanceCounter((LARGE_INTEGER*)&Stop);
+ //cout << (Stop-Start)*1000/Freq << endl;
+
+ return 0;
+}
+
diff --git a/tools/mhmake/src/mhmakefileparser.cpp b/tools/mhmake/src/mhmakefileparser.cpp
new file mode 100644
index 000000000..a359de117
--- /dev/null
+++ b/tools/mhmake/src/mhmakefileparser.cpp
@@ -0,0 +1,1451 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+#include "util.h"
+#include "md5.h"
+
+#include "mhmakefileparser.h"
+#include "rule.h"
+#include "flexlexer.h"
+#include "mhmakeparser.hpp"
+
+commandqueue mhmakefileparser::sm_CommandQueue;
+stack<yy::mhmakeparser*> mhmakefileparser::sm_ParserStack; // Keeps track of the currently active parser
+
+string mhmakefileparser::GetFileNameLineNo(void)
+{
+ if (!sm_ParserStack.empty())
+ {
+ yy::mhmakeparser* pParser=sm_ParserStack.top();
+ yy::position *pPos=pParser->GetCurPos();
+ return pParser->GetInputFilename()+":"+stringify(pPos->line)+" ";
+ }
+ else
+ return g_EmptyString; // Currently not parsing, this is a run-time error after parsing
+}
+
+///////////////////////////////////////////////////////////////////////////////
+int mhmakefileparser::ParseFile(const fileinfo *pFileInfo, const fileinfo *pMakeDir)
+{
+ if (pMakeDir)
+ {
+ m_MakeDir=pMakeDir;
+ m_Variables[CURDIR]=m_MakeDir->GetQuotedFullFileName();
+ }
+
+ ifstream yyin(pFileInfo->GetFullFileName().c_str(),ios_base::in);
+ if (yyin.fail())
+ {
+ cerr << "Error opening makefile: "<<pFileInfo->GetQuotedFullFileName()<<endl;
+ return 1;
+ }
+
+ mhmakeFlexLexer theLexer(&yyin);
+
+ theLexer.m_InputFileName=pFileInfo->GetFullFileName();
+ theLexer.m_pMakefileParser=this;
+
+ yy::mhmakeparser Parser(this,&theLexer);
+ sm_ParserStack.push(&Parser);
+ int Ret=Parser.parse();
+ sm_ParserStack.pop();
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+int mhmakefileparser::ParseString(const string &StringIn)
+{
+ basic_istringstream<char> yyin(StringIn.c_str());
+
+ mhmakeFlexLexer theLexer(&yyin);
+
+ theLexer.m_InputFileName=string("eval(")+StringIn+")";
+ theLexer.m_pMakefileParser=this;
+
+ yy::mhmakeparser Parser(this,&theLexer);
+ sm_ParserStack.push(&Parser);
+ int Ret=Parser.parse();
+ sm_ParserStack.pop();
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+bool mhmakefileparser::IsDefined(const string &Var) const
+{
+ bool Ret = m_Variables.find(Var)!=m_Variables.end();
+ if (!Ret)
+ {
+ string Env=GetFromEnv(Var);
+ if (!Env.empty())
+ {
+ Ret=true;
+ }
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+static inline size_t SkipUntilQuote(const string &Expr,size_t i,char Char)
+{
+ while (Expr[i++]!=Char) ;
+ return i;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Splits expression on the Item, but the item may not occur within
+// a macro or quoted string
+static pair<string,string> SplitExpr(const string &Expr,char Item)
+{
+ size_t i=0;
+ char Char=Expr[i++];
+ while (Char!=Item)
+ {
+ if (Char=='"' || Char=='\'')
+ {
+ i=SkipUntilQuote(Expr,i,Char);
+ }
+ else if (Char=='$')
+ {
+ i=SkipMakeExpr(Expr,i);
+ }
+ Char=Expr[i++];
+ }
+ return pair<string,string>(Expr.substr(0,i-1),Expr.substr(i));
+}
+
+///////////////////////////////////////////////////////////////////////////////
+bool mhmakefileparser::IsEqual(const string &EqualExpr) const
+{
+ string Expr=ExpandExpression(EqualExpr);
+ const char *pStr=Expr.c_str();
+ const char *pTmp=pStr;
+ while (*pTmp && *pTmp!=',') pTmp++;
+ ptrdiff_t Pos=pTmp-pStr;
+ size_t Size=Expr.size();
+ pTmp=pStr+Size-1;
+ while (pTmp>pStr && strchr(" \t",*pTmp))
+ {
+ pTmp--;
+ }
+ if (2*Pos != pTmp-pStr)
+ {
+ return false;
+ }
+ pTmp=pStr;
+ const char *pTmp2=pTmp+Pos+1;
+ if (*pTmp=='(')
+ {
+ pTmp++;
+ Pos--;
+ }
+ for (int i=0; i<Pos; i++)
+ {
+ if (pTmp[i]!=pTmp2[i])
+ {
+ return false;
+ }
+ }
+ return true;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+inline string mhmakefileparser::ExpandExpression(const string &ExprIn) const
+{
+ bool Recurse=true;
+ string Ret(ExprIn);
+ while (Recurse)
+ {
+ Recurse=false;
+ string Expr(Ret);
+ Ret.clear();
+
+ size_t i=0;
+ size_t Length=Expr.size();
+ string ToAdd;
+ while (i<Length)
+ {
+ char Char=Expr[i++];
+ if (Char=='$')
+ {
+ size_t inew=SkipMakeExpr(Expr,i);
+ i++;
+ if (inew>i)
+ {
+ ToAdd=ExpandMacro(Expr.substr(i,inew-i-1));
+ i=inew;
+ }
+ else
+ {
+ // This is a single character expression
+ ToAdd=ExpandMacro(string(1,Expr[i-1]));
+ }
+ if (ToAdd.find('$')!=string::npos && ToAdd.length()!=1)
+ {
+ Recurse=true;
+ }
+ Ret+=ToAdd;
+ }
+ else
+ {
+ Ret+=Char;
+ }
+ }
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::ExpandMacro(const string &Expr) const
+{
+ const char *pTmp=Expr.c_str();
+ /* First remove leading spaces */
+ while (*pTmp==' ' || *pTmp=='\t') pTmp++;
+ const char *pVar=pTmp;
+ while (*pTmp && *pTmp!=' ' && *pTmp!='\t' && *pTmp!=':')
+ {
+ if (*pTmp=='$' && pTmp[1]) // We have a macro expansion inside a macro expansion, so recurse Do not consider isolated $ (This was a $$)
+ {
+ return ExpandMacro(ExpandExpression(Expr));
+ }
+ pTmp++;
+ }
+ const char *pVarEnd=pTmp;
+ char Type=*pTmp++;
+ while (*pTmp && (*pTmp==' ' || *pTmp=='\t')) pTmp++;
+ if (Type&&*pTmp)
+ { // We have a match for the regular expression ^([^ \\t:]+)([: \\t])[ \\t]*(.+)
+ if (Type==':')
+ {
+ #ifdef WIN32
+ bool IsFileName=false;
+ if (pVarEnd-pVar == 1 && (*pVar=='<' || *pVar =='@'))
+ IsFileName=true;
+ #endif
+ string ToSubst=ExpandExpression(ExpandVar(string(pVar,pVarEnd)));
+ const char *pSrc=pTmp;
+ const char *pStop=pSrc;
+ while (*pStop!='=') pStop++;
+ const char *pTo=pStop+1;
+ string SrcStr(ExpandExpression(string(pSrc,pStop)));
+ string ToStr(pTo); // Do not expand yet to be able to use % inside a macro
+ #ifdef WIN32
+ if (IsFileName)
+ {
+ matchres Res;
+ string FileName(UnquoteFileName(ToSubst));
+ if (PercentMatch(FileName,UnquoteFileName(SrcStr),&Res))
+ {
+ FileName=ReplaceWithStem(UnquoteFileName(ToStr),Res.m_Stem);
+ }
+ return QuoteFileName(FileName);
+ }
+ #endif
+ return Substitute(ToSubst,SrcStr,ToStr);
+ }
+ else if (Type==' ' || Type == '\t')
+ {
+ string Arg(pTmp);
+ string Func(pVar,pVarEnd);
+ function_f pFunc=m_Functions[Func];
+ #ifdef _DEBUG
+ if (pFunc)
+ {
+ return (this->*pFunc)(Arg);
+ }
+ else
+ {
+ throw GetFileNameLineNo() + "Unknown function specified in macro: "+Func;
+ }
+ #else
+ return (this->*pFunc)(Arg);
+ #endif
+ }
+ else
+ {
+ #ifdef _DEBUG
+ throw string("Fatal error in ExpandMacro (bug in mhmake ? ? ?)");
+ #else
+ return g_EmptyString;
+ #endif
+ }
+ }
+ else
+ {
+ #ifdef _DEBUG
+ if (Expr.find('$')!=string::npos && Expr.length()!=1)
+ throw(string("Bug in mhmake: wasn't expecting a $ sign in: ")+Expr);
+ #endif
+ string Ret=ExpandVar(Expr);
+ if (Ret.length()>1)
+ return ExpandExpression(Ret);
+ else
+ return Ret;
+}
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string mhmakefileparser::ExpandVar(const string &Var) const
+{
+ map<string,string>::const_iterator pIt=m_Variables.find(Var);
+ if (pIt==m_Variables.end())
+ {
+ if (Var.size()==1)
+ {
+ char Char=Var[0];
+ if (m_RuleThatIsBuild)
+ {
+ switch (Char)
+ {
+ case '<': // return first prerequisit
+#ifdef _DEBUG
+ if (!m_RuleThatIsBuild->GetDeps().size())
+ {
+ return "<No Dependencies defined.>";
+ }
+#endif
+ return m_RuleThatIsBuild->GetDeps()[0]->GetQuotedFullFileName();
+ case '@': // return full target file name
+ return m_RuleThatIsBuild->GetQuotedFullFileName();
+ case '*': // return stem
+ return m_RuleThatIsBuild->GetRule()->GetStem();
+ case '^': // return all prerequisits
+ return m_RuleThatIsBuild->GetPrerequisits();
+ case '/':
+ return OSPATHSEPSTR;
+ case '$':
+ return Var;
+ case 'n':
+ return "\n";
+ default:
+ break;
+ }
+ }
+ else
+ {
+ switch (Char)
+ {
+ case '<': // return first prerequisit
+ case '@': // return full target file name
+ case '*': // return stem
+ case '^': // return all prerequisits
+ case '$': // $$ expansion
+ return Var; // To make comparing of rules more accurate
+ case '/':
+ return OSPATHSEPSTR;
+ case 'n':
+ return "\n";
+ default:
+ break;
+ }
+ }
+ }
+ string Env=GetFromEnv(Var);
+ if (Env.empty())
+ {
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ {
+ cout<<"Warning: Variable "<<Var<<" not found\n";
+ }
+ #endif
+ return g_EmptyString;
+ }
+ else
+ return Env;
+ }
+ else
+ return pIt->second;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::SplitToItems(const string &String,vector<fileinfo*> &Items) const
+{
+ const char *pTmp=String.c_str();
+ while (*pTmp)
+ {
+ string Item;
+ pTmp=NextItem(pTmp,Item);
+ if (!Item.empty())
+ {
+ Items.push_back(GetFileInfo(Item,m_MakeDir));
+ }
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::ParseBuildedIncludeFiles()
+{
+ vector<string>::iterator It=m_ToBeIncludeAfterBuild.begin();
+ while (It!=m_ToBeIncludeAfterBuild.end())
+ {
+ int result=ParseFile(GetFileInfo(*It,m_MakeDir));
+ if (result)
+ {
+ throw string("Error parsing ")+*It;
+ }
+ It++;
+ }
+}
+
+#ifdef _DEBUG
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::PrintVariables(bool Expand) const
+{
+ map<string,string>::const_iterator It=m_Variables.begin();
+ while (It!=m_Variables.end())
+ {
+ if (Expand)
+ {
+ try
+ {
+ cout<<It->first<<" : "<<ExpandExpression(It->second)<<endl;
+ }
+ catch (...)
+ {
+ cout<<endl;
+ }
+ }
+ else
+ {
+ cout<<It->first<<" : "<<It->second<<endl;
+ }
+ It++;
+ }
+ if (m_pEnv)
+ {
+ cout << "Environment overruled:\n";
+#ifdef WIN32
+ char *pEnv=m_pEnv;
+ while (*pEnv)
+ {
+ cout<<pEnv<<endl;
+ pEnv+=strlen(pEnv)+1;
+ }
+#else
+ char **pEnv=m_pEnv;
+ while (*pEnv)
+ {
+ cout<<*pEnv<<endl;
+ pEnv++;
+ }
+#endif
+ }
+}
+#endif
+
+//#define PAGETOSTRING(Nr) #Nr
+//#define PAGETONBR(Nr) PAGETOSTRING(##Nr)
+//#pragma message("ar=" PAGETONBR(NULL) ";")
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::AddRule()
+{
+ fileinfoarray::iterator pIt=m_pCurrentItems->begin();
+ while (pIt!=m_pCurrentItems->end())
+ {
+ if ((*pIt)->GetFullFileName().find('%')!=string::npos)
+ {
+ IMPLICITRULE::AddImplicitRule(*pIt,*m_pCurrentDeps,m_pCurrentRule);
+ }
+ else
+ {
+ // If we had a double colon we must make sure that the target is always build
+ if (m_DoubleColonRule)
+ {
+ (*pIt)->SetNotExist();
+ }
+ (*pIt)->SetRuleIfNotExist(m_pCurrentRule);
+ if (!m_pCurrentRule)
+ (*pIt)->AddDeps(*m_pCurrentDeps);
+ else
+ (*pIt)->InsertDeps(*m_pCurrentDeps);
+ if (!m_FirstTarget)
+ { // Only check this if the rule is not an implicit rule
+ m_FirstTarget=(*m_pCurrentItems)[0];
+ }
+ }
+ pIt++;
+ }
+ m_pCurrentItems=NULL;
+ m_pCurrentRule=NullRule;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::GetAutoDeps(const fileinfo *pFirstDep, deps_t &Autodeps)
+{
+ /* Here we have to scan only c/c++ headers so skip certain extensions */
+ const char *pFullName=pFirstDep->GetFullFileName().c_str();
+ const char *pExt=strrchr(pFullName,'.');
+ bool bPython=false;
+ if (pExt)
+ {
+ if (!_stricmp(pExt+1,"py"))
+ bPython=true;
+ }
+
+ FILE *pIn=fopen(pFullName,"r");
+ if (!pIn)
+ return;
+
+ char IncludeList[255];
+ int PrevRet=0;
+ int Ret=fgetc(pIn);
+ while(Ret!=EOF)
+ {
+ char Type[2];
+ bool bFound=false;
+ if (bPython)
+ {
+ Type[0]='"';
+ if (Ret=='i')
+ {
+ Ret=fscanf(pIn,"mport %254[^\"\n]",IncludeList);
+ if (Ret==1)
+ {
+ if (IncludeList[0]!='*')
+ bFound=true;
+ }
+ }
+ }
+ else
+ {
+ if (PrevRet=='/')
+ {
+ if (Ret=='/')
+ {
+ /* This is a C++ command so read until the next line-feed */
+ do
+ {
+ Ret=fgetc(pIn);
+ } while (Ret!='\n' && Ret!=EOF);
+ }
+ else if (Ret=='*')
+ {
+ /* This is a standard C comment, so read until then end of the command */
+ do
+ {
+ PrevRet=Ret;
+ Ret=fgetc(pIn);
+ } while ((PrevRet!='*' || Ret!='/') && Ret!=EOF);
+ }
+ }
+ else if (Ret=='#' || Ret=='.')
+ {
+ if (Ret=='#')
+ {
+ Ret=fscanf(pIn,"%*[ \t]");
+ Ret=fscanf(pIn,"include %1[\"<]%254[^>\"]%*[\">]",(char*)&Type,IncludeList);
+ }
+ else
+ Ret=fscanf(pIn,"import %1[\"<]%254[^>\"]%*[\">]",(char*)&Type,IncludeList);
+ if (Ret==2)
+ {
+ bFound=true;
+ }
+ }
+ }
+ if (bFound)
+ {
+ const char *pTmp=IncludeList;
+ while (*pTmp)
+ {
+ string IncludeFile;
+ pTmp=NextItem(pTmp,IncludeFile," \t,");
+ if (bPython)
+ IncludeFile+=".py";
+
+ if (SkipHeaderFile(IncludeFile))
+ continue;
+ #ifdef _DEBUG
+ m_ImplicitSearch++; // This is to avoid warnings of targets that does not exist
+ #endif
+ if (Type[0]=='"')
+ {
+ fileinfo *pInclude=GetFileInfo(IncludeFile,pFirstDep->GetDir());
+ /* Add the dependency when the file alrady exist or there is a rule available to be build */
+ mh_time_t Date=BuildTarget(pInclude);
+ if (Date.DoesExist()) // Try to build the target, and add it if it exists after building
+ {
+ deps_t::const_iterator pFind=Autodeps.find(pInclude);
+ if (pFind==Autodeps.end())
+ {
+ Autodeps.insert(pInclude);
+ GetAutoDepsIfNeeded(pInclude,pInclude);
+ }
+ }
+ }
+ const refptr<fileinfoarray> IncludeDirs=GetIncludeDirs();
+ fileinfoarray::const_iterator It=IncludeDirs->begin();
+ while (It<IncludeDirs->end())
+ {
+ fileinfo *pInclude=GetFileInfo(IncludeFile,*It);
+ mh_time_t Date=BuildTarget(pInclude);
+ if (Date.DoesExist()) // Try to build the target, and add it if it exists after building
+ {
+ deps_t::const_iterator pFind=Autodeps.find(pInclude);
+ if (pFind==Autodeps.end())
+ {
+ Autodeps.insert(pInclude);
+ GetAutoDepsIfNeeded(pInclude,pInclude);
+ }
+ break;
+ }
+ It++;
+ }
+ #ifdef _DEBUG
+ m_ImplicitSearch--;
+ #endif
+ }
+ }
+ PrevRet=Ret;
+ Ret=fgetc(pIn);
+ }
+ fclose(pIn);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+void mhmakefileparser::GetAutoDepsIfNeeded(fileinfo *pTarget, const fileinfo *pFirstDep)
+{
+ autodeps_entry_t &Autodeps=m_AutoDeps[pTarget];
+ if (!Autodeps.first)
+ {
+ Autodeps.first=true;
+ /* We are going to rescan, so throw away the old. */
+ Autodeps.second.clear();
+ GetAutoDeps(pFirstDep,Autodeps.second);
+ // Now add these dependencies also to the rules
+ deps_t::iterator It=Autodeps.second.begin();
+ while (It!=Autodeps.second.end())
+ {
+ pTarget->AddDep(*It);
+ It++;
+ }
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+void mhmakefileparser::UpdateAutomaticDependencies(fileinfo *pTarget)
+{
+ if (pTarget->IsAutoDepExtention())
+ {
+ // we have to search for the include files in the first dependency of Target
+ vector<fileinfo*> &Deps=pTarget->GetDeps();
+ if (!Deps.size())
+ return; // There is no first dep
+ fileinfo *pFirstDep=Deps[0];
+ GetAutoDepsIfNeeded(pTarget,pFirstDep);
+ SetAutoDepsDirty();
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::UpdateNoRuleAutomaticDependencies(fileinfo *pTarget)
+{
+ // we have to search for the include files in the Target
+ deps_t Autodeps;
+ GetAutoDeps(pTarget,Autodeps);
+ // Now add these dependencies also to the rules
+ deps_t::iterator It=Autodeps.begin();
+ while (It!=Autodeps.end())
+ {
+ pTarget->AddDep(*It);
+ It++;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+const refptr<fileinfoarray> mhmakefileparser::GetIncludeDirs() const
+{
+ string Includes=ExpandExpression("$(INCLUDES)");
+ if (!m_pIncludeDirs || Includes != m_IncludeDirs)
+ {
+ ((mhmakefileparser*)this)->m_IncludeDirs=Includes;
+ ((mhmakefileparser*)this)->m_pIncludeDirs=refptr<fileinfoarray>(new fileinfoarray);
+ if (Includes.empty()) // If not defined try a default path
+ Includes="include inc .."OSPATHSEPSTR"include .."OSPATHSEPSTR"inc";
+ const char *pTmp=Includes.c_str();
+ while (*pTmp)
+ {
+ string Item;
+ pTmp=NextItem(pTmp,Item);
+ fileinfo *pIncDir=GetFileInfo(Item,m_MakeDir);
+ if (pIncDir->Exists() || pIncDir->GetRule())
+ ((mhmakefileparser*)this)->m_pIncludeDirs->push_back(pIncDir);
+ }
+ }
+ return m_pIncludeDirs;
+}
+
+static void ReadStr(FILE *pFile,char *Str)
+{
+ int i=0;
+ while (1)
+ {
+ Str[i]=fgetc(pFile);
+#ifdef _DEBUG
+ if (Str[i]==EOF)
+ {
+ cout<<"Premature end of depency file.\n";
+ Str[i]=0;
+ return;
+ }
+#endif
+ if (Str[i]=='\n')
+ break;
+ i++;
+ }
+ Str[i]='\0';
+}
+
+void mhmakefileparser::LoadAutoDepsFile(fileinfo *pDepFile)
+{
+ if (m_AutoDepFileLoaded && m_AutoDepFileLoaded==pDepFile)
+ return; /* This autodep file is already loaded. */
+
+ m_AutoDepFileLoaded=pDepFile;
+
+ FILE *pIn=fopen(pDepFile->GetFullFileName().c_str(),"rb");
+ if (!pIn)
+ {
+ cerr << "Error opening autodep file "<<pDepFile->GetQuotedFullFileName()<<endl;
+ return;
+ }
+ if (1!=fread(&m_EnvMd5_32,sizeof(m_EnvMd5_32),1,pIn))
+ {
+ cerr << "Wrong format of autodep file "<<pDepFile->GetQuotedFullFileName()<<endl;
+ fclose(pIn);
+ return;
+ }
+#ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "Reading Env Md5 from "<<pDepFile->GetQuotedFullFileName()<<": "<<hex<<m_EnvMd5_32<<endl;
+#endif
+ char UsedEnvVars[1024];
+ ReadStr(pIn,UsedEnvVars);
+ SetVariable(USED_ENVVARS,UsedEnvVars);
+
+ char FileName[MAX_PATH];
+ ReadStr(pIn,FileName);
+ while (FileName[0])
+ {
+ fileinfo *pTarget=GetFileInfo(FileName,m_MakeDir);
+ autodeps_entry_t &Autodeps=m_AutoDeps[pTarget];
+ ReadStr(pIn,FileName);
+ while (FileName[0])
+ {
+ if (!g_ForceAutoDepRescan) /* If we are forcing the autodepscan we do not have to load the dependencies. */
+ {
+ fileinfo *pDep=GetFileInfo(FileName,m_MakeDir);
+ Autodeps.second.insert(pDep);
+ pTarget->AddDep(pDep);
+ }
+ ReadStr(pIn,FileName);
+ }
+ ReadStr(pIn,FileName);
+ }
+
+ uint32 Md5_32;
+ bool MakeNotDirty=true;
+ while (fread(&Md5_32,sizeof(Md5_32),1,pIn))
+ {
+ ReadStr(pIn,FileName);
+
+ fileinfo *pTarget=GetAbsFileInfo(FileName);
+
+ if (!pTarget->CompareMd5_32(0) && !pTarget->CompareMd5_32(Md5_32))
+ {
+ MakeNotDirty=false; /* BuildTarget had set the dirty flag, but since the md5 did not change it was a false dirty. This is for BuildTargets called before this routine */
+ #ifdef _DEBUG
+ cout << "Warning: trying to set to different md5's for Target "<<pTarget->GetQuotedFullFileName()<<" Old: "<<hex<<pTarget->GetCommandsMd5_32()<<" New: "<<Md5_32<<endl;
+ #endif
+ }
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "Setting Md5 for Target "<<pTarget->GetQuotedFullFileName()<<" to "<<hex<<Md5_32<<endl;
+ #endif
+ pTarget->SetCommandsMd5_32(Md5_32); // If it was already there, just update the md5 value
+
+ AddTarget(pTarget);
+ }
+ if (MakeNotDirty)
+ ClearAutoDepsDirty();
+
+ fclose(pIn);
+}
+
+void mhmakefileparser::SaveAutoDepsFile()
+{
+ if (!IsAutoDepsDirty())
+ return;
+
+ if (g_Clean
+#ifdef _DEBUG
+ || g_DoNotExecute || g_GenProjectTree
+#endif
+ )
+ return; // do not save on clean or if no commands are executed
+
+ string DepFile=ExpandVar(AUTODEPFILE);
+ if (!DepFile.size())
+ {
+ return;
+ }
+ fileinfo *pDepFile=GetFileInfo(DepFile,m_MakeDir);
+
+#ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout<<"Saving automatic dependency file "<<DepFile<<endl;
+#endif
+
+ FILE *pOut=fopen(pDepFile->GetFullFileName().c_str(),"wb");
+ if (!pOut)
+ {
+ /* Maybe it is because the directory does not exist, so try to create this first */
+ if (!MakeDirs(pDepFile->GetDir()))
+ {
+ #ifdef _DEBUG
+ if (!g_DoNotExecute)
+ #endif
+ cerr << "Error creating dir "<<pDepFile->GetDir()->GetFullFileName()<<endl;
+ return;
+ }
+ pOut=fopen(pDepFile->GetFullFileName().c_str(),"wb");
+
+ if (!pOut)
+ {
+ #ifdef _DEBUG
+ if (!g_DoNotExecute)
+ #endif
+ cerr << "Error creating file "<<DepFile<<endl;
+ return;
+ }
+ }
+ // First update the USER_ENVVARS variable and then save it to the dep file together with the md5 string
+ CreateUSED_ENVVARS();
+ uint32 Md5_32=CreateEnvMd5_32();
+ fwrite(&Md5_32,sizeof(Md5_32),1,pOut);
+ fprintf(pOut,"%s\n",m_Variables[USED_ENVVARS].c_str());
+
+ autodeps_t::const_iterator It=m_AutoDeps.begin();
+ while (It!=m_AutoDeps.end())
+ {
+ if (!It->second.second.empty())
+ {
+ fprintf(pOut,"%s\n",It->first->GetFullFileName().c_str());
+ deps_t::const_iterator DepIt=It->second.second.begin();
+ while (DepIt!=It->second.second.end())
+ {
+ fprintf(pOut,"%s\n",(*DepIt)->GetFullFileName().c_str());
+ DepIt++;
+ }
+ fprintf(pOut,"\n");
+ }
+ It++;
+ }
+ /* Now save the Md5 strings */
+ fprintf(pOut,"\n");
+
+ set<const fileinfo *>::iterator pIt=m_Targets.begin();
+ while (pIt!=m_Targets.end())
+ {
+ if (!(*pIt)->CompareMd5_32(0))
+ {
+ (*pIt)->WriteMd5_32(pOut);
+ string FileName=(*pIt)->GetFullFileName();
+ fwrite(FileName.c_str(),FileName.size(),1,pOut);
+ fputc('\n',pOut);
+ }
+ pIt++;
+ }
+
+ fclose(pOut);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Uses the SKIPHEADERS variable to check if we have to skip the header in
+// the automatic dependency scanning
+
+bool mhmakefileparser::SkipHeaderFile(const string &FileName)
+{
+ if (!m_SkipHeadersInitialized)
+ {
+ m_SkipHeadersInitialized=true;
+ string HeadersToSkip=ExpandVar(SKIPHEADERS);
+ const char *pTmp=HeadersToSkip.c_str();
+ while (*pTmp)
+ {
+ string Item;
+ pTmp=NextItem(pTmp,Item);
+ if (Item.find('%')==string::npos)
+ {
+ m_SkipHeaders.insert(Item);
+ }
+ else
+ {
+ m_PercentHeaders.push_back(Item);
+ }
+ }
+ }
+ if (m_SkipHeaders.find(FileName)!=m_SkipHeaders.end())
+ return true;
+
+ vector<string>::const_iterator It=m_PercentHeaders.begin();
+ vector<string>::const_iterator ItEnd=m_PercentHeaders.end();
+ while (It!=ItEnd)
+ {
+ if (PercentMatch(FileName,*It++))
+ return true;
+ }
+
+ return false;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::SetExport(const string &Var, const string &Val)
+{
+ m_Exports.insert(Var);
+#ifdef WIN32
+ if (!m_pEnv)
+ {
+ /* Environment not created yet, so create one */
+ char *pEnv=GetEnvironmentStrings();
+ char *pEnd=pEnv;
+ while (*pEnd)
+ {
+ while (*pEnd++);
+ }
+ size_t Len=pEnd-pEnv+1;
+ m_pEnv=(char*)malloc(Len);
+ memcpy(m_pEnv,pEnv,Len);
+ m_EnvLen=Len;
+ FreeEnvironmentStrings(pEnv);
+ }
+ /* First check if the variable is in the environment, if so remove it first */
+ char *pEnv=m_pEnv;
+ while (*pEnv)
+ {
+ const char *pVar=Var.c_str();
+ char *pStart=pEnv;
+ while (*pEnv!='=' && *pEnv==*pVar)
+ {
+ pEnv++; pVar++;
+ }
+ if (*pEnv=='=' && !*pVar)
+ {
+ /* Variable found, remove it */
+ while (*pEnv++);
+ m_EnvLen-=pEnv-pStart;
+ while (*pEnv)
+ {
+ while (*pEnv)
+ {
+ *pStart=*pEnv++;
+ pStart++;
+ }
+ *pStart=*pEnv++;
+ pStart++;
+ }
+ *pStart=*pEnv;
+ break;
+ }
+ while (*pEnv++);
+ }
+ size_t VarLen=Var.length();
+ size_t ValLen=Val.length();
+ size_t Extra=VarLen+ValLen+2;
+ /* Add the variable at the end */
+ m_pEnv=(char*)realloc(m_pEnv,m_EnvLen+Extra);
+ pEnv=m_pEnv+m_EnvLen-1;
+ memcpy(pEnv,Var.c_str(),VarLen);
+ pEnv+=VarLen;
+ *pEnv++='=';
+ memcpy(pEnv,Val.c_str(),ValLen);
+ pEnv+=ValLen;
+ *pEnv++='\0';
+ *pEnv++='\0';
+ m_EnvLen+=Extra;
+#else
+ if (!m_pEnv)
+ {
+ /* Environment not created yet, so create one */
+ char **pEnv=environ;
+ char **pEnd=pEnv;
+ int Len=1;
+ while (*pEnd)
+ {
+ Len++;
+ pEnd++;
+ }
+ m_EnvLen=Len;
+ m_pEnv=(char**)malloc(Len*sizeof(pEnv));
+ int i=0;
+ while (*pEnv)
+ {
+ m_pEnv[i]=strdup(*pEnv);
+ i++;
+ pEnv++;
+ }
+ m_pEnv[i]=NULL;
+ }
+ /* First check if the variable is in the environment, if so replace it */
+ char **pEnv=m_pEnv;
+ while (*pEnv)
+ {
+ const char *pVar=Var.c_str();
+ char *pStart=*pEnv;
+ char *pTmp=pStart;
+ while (*pTmp!='=' && *pTmp==*pVar)
+ {
+ pTmp++; pVar++;
+ }
+ if (*pTmp=='=' && !*pVar)
+ {
+ free(*pEnv);
+ *pEnv=strdup((Var+"="+Val).c_str());
+ break;
+ }
+ pEnv++;
+ }
+ if (!*pEnv)
+ {
+ // Add it at the end of the list
+ m_pEnv=(char**)realloc(m_pEnv,(m_EnvLen+1)*sizeof(*pEnv));
+ m_pEnv[m_EnvLen-1]=strdup((Var+"="+Val).c_str());
+ m_pEnv[m_EnvLen++]=NULL;
+ }
+
+#endif
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void mhmakefileparser::SetvPath(const string &Pattern, const string &Path)
+{
+ // First create the array of directory from the Path parameter. For now all entries need to
+ // be valid directories (extra checking). This could be improved by checking if there
+ // is a rule for creating the directory entry, but like first said, not for now.
+ refptr<fileinfoarray> pDirArray=new fileinfoarray;
+
+ const char *pTmp=Path.c_str();
+ while (*pTmp)
+ {
+ string Item;
+ pTmp=NextItem(pTmp,Item," \t:;");
+ if (!Item.empty())
+ {
+ fileinfo *pDir=GetFileInfo(Item,m_MakeDir);
+ if (!pDir->IsDir())
+ {
+ #ifdef WIN32
+ // On windows this could happen if a full pathname was specified, so we try together
+ // with the next item to check if this is not a valid directories
+ // but only if the the length of the item was 1 namely the driver letter
+ if (Item.length()==1)
+ {
+ string Rest;
+ pTmp=NextItem(pTmp,Rest," \t:;");
+ pDir=GetFileInfo(Item+":"+Rest,m_MakeDir);
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo && !pDir->IsDir())
+ throw(pDir->GetFullFileName()+" is not a valid directory.");
+ #endif
+ }
+ #ifdef _DEBUG
+ else if (g_PrintAdditionalInfo)
+ cout << pDir->GetFullFileName() << " is not a valid directory.\n";
+ #endif
+ #else
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << pDir->GetFullFileName() << " is not a valid directory.\n";
+ #endif
+ #endif
+ }
+ pDirArray->push_back(pDir);
+ }
+ }
+ m_vPath.push_back(pair<string, refptr<fileinfoarray> >(Pattern,pDirArray));
+}
+
+///////////////////////////////////////////////////////////////////////////////
+//
+// Search for the target using the vPath
+fileinfo* mhmakefileparser::SearchvPath(const fileinfo* pTarget)
+{
+ string TargetName=pTarget->GetName();
+ vector< pair< string, refptr<fileinfoarray> > >::iterator vPathIt=m_vPath.begin();
+ while (vPathIt!=m_vPath.end())
+ {
+ matchres Res;
+
+ if (PercentMatch(TargetName,vPathIt->first,&Res))
+ {
+ fileinfoarray::iterator pIt=vPathIt->second->begin();
+ while (pIt!=vPathIt->second->end())
+ {
+ fileinfo* pNewTarget=GetFileInfo(TargetName,*pIt);
+ mh_time_t TargetDate=StartBuildTarget(pNewTarget,false);
+ if (!TargetDate.IsDateValid())
+ TargetDate=WaitBuildTarget(pNewTarget);
+ if (pNewTarget->GetDate().DoesExist())
+ return pNewTarget;
+ pIt++;
+ }
+ }
+ vPathIt++;
+ }
+ return NULL;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+//
+//Checks if the variables retreived from the environment or command-line have been
+//changed. Do this at late as possible because they can also be changed in theLexer
+//makefiles.
+//
+void mhmakefileparser::CheckEnv(void)
+{
+ if (CompareEnv())
+ {
+ #ifdef _DEBUG
+ if (!g_GenProjectTree)
+ cout << "Rebuilding everything of "<< m_MakeDir->GetQuotedFullFileName() <<" because environment and/or command-line variables have been changed.\n";
+ #endif
+ SetRebuildAll();
+ }
+
+}
+
+///////////////////////////////////////////////////////////////////////////////
+//
+//Create a Md5 string from m_GlobalCommandLineVars and USED_ENVVARS
+//
+
+
+static bool SkipVar(const string &Var)
+{
+ if (Var==WC_REVISION)
+ return true;
+ if (Var==WC_URL)
+ return true;
+ if (Var==MAKE)
+ return true;
+ return false;
+}
+
+#define DBGOUT(stuff)
+
+uint32 mhmakefileparser::CreateEnvMd5_32() const
+{
+ md5_context ctx;
+ string Md5;
+ string EnvVars=ExpandVar(USED_ENVVARS);
+ const char *pTmp=EnvVars.c_str();
+
+ // Now create the md5 string
+ md5_starts( &ctx );
+
+ DBGOUT(cout << "MD5 of " << m_MakeDir->GetQuotedFullFileName() << endl);
+
+ while (*pTmp)
+ {
+ string Var;
+ pTmp=NextItem(pTmp,Var,";");
+ if (!SkipVar(Var))
+ {
+ string Val=ExpandVar(Var);
+ transform(Val.begin(),Val.end(),Val.begin(),(int(__CDECL *)(int))toupper);
+ DBGOUT(cout << GetMakeDir()->GetQuotedFullFileName() << " -> Setting GetFromEnv var " << Var << " to " << Val << endl);
+ md5_update( &ctx, (uint8 *) Var.c_str(), (unsigned long)Var.size());
+ md5_update( &ctx, (uint8 *) "=", 1);
+ md5_update( &ctx, (uint8 *) Val.c_str(), (unsigned long)Val.size());
+ }
+ }
+
+ return md5_finish32( &ctx);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Makes sure that the makefile exports are set in the environment
+
+bool mhmakefileparser::CompareEnv() const
+{
+ uint32 Md5_32=CreateEnvMd5_32();
+#ifdef _DEBUG
+ if (!g_GenProjectTree && Md5_32!=m_EnvMd5_32)
+ cout << "Environment has been changed: "<<hex<<m_EnvMd5_32<<" to "<<Md5_32<<endl;
+#endif
+ return Md5_32!=m_EnvMd5_32;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Makes sure that the makefile exports are set in the environment
+mh_time_t mhmakefileparser::m_sBuildTime;
+
+void mhmakefileparser::InitBuildTime()
+{
+ m_sBuildTime=time(NULL);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Returns a variable from the environment or from the command line and adds it the m_UsedEnvVars
+string mhmakefileparser::GetFromEnv(const string &Var, bool Cache) const
+{
+ /* First we look into the command line variables, before we are looking in the environment */
+ map<string,string>::const_iterator pLineFind=m_CommandLineVars.find(Var);
+ if (pLineFind!=m_CommandLineVars.end())
+ {
+ ((mhmakefileparser*)this)->m_UsedEnvVars.insert(Var);
+ if (Cache)
+ ((mhmakefileparser*)this)->m_Variables[Var]=pLineFind->second;
+ return pLineFind->second;
+ }
+
+ const char *pEnv=getenv(Var.c_str());
+ if (!pEnv)
+ {
+ return g_EmptyString;
+ }
+ ((mhmakefileparser*)this)->m_UsedEnvVars.insert(Var);
+
+ if (Cache)
+ ((mhmakefileparser*)this)->m_Variables[Var]=pEnv;
+ return pEnv;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Creates the variable USER_ENVVARS to be saved in the autodeps file
+//
+
+void mhmakefileparser::CreateUSED_ENVVARS()
+{
+
+ set<string> Variables;
+
+ set<string>::const_iterator It=m_UsedEnvVars.begin();
+ set<string>::const_iterator ItEnd=m_UsedEnvVars.end();
+
+ while (It!=ItEnd)
+ {
+ string Var=*It;
+ if (!SkipVar(Var))
+ {
+ transform(Var.begin(),Var.end(),Var.begin(),(int(__CDECL *)(int))toupper);
+ Variables.insert(Var);
+ }
+ It++;
+ }
+
+ It=m_Exports.begin();
+ ItEnd=m_Exports.end();
+
+ while (It!=ItEnd)
+ {
+ string Var=*It;
+ if (!SkipVar(Var))
+ {
+ transform(Var.begin(),Var.end(),Var.begin(),(int(__CDECL *)(int))toupper);
+ Variables.insert(Var);
+ }
+ It++;
+ }
+
+ map<string,string>::const_iterator CLItEnd=loadedmakefile::sm_Statics.m_GlobalCommandLineVars.end();
+ map<string,string>::const_iterator CLIt=loadedmakefile::sm_Statics.m_GlobalCommandLineVars.begin();
+ while (CLIt!=CLItEnd)
+ {
+ string Var=CLIt->first;
+ if (!SkipVar(Var))
+ {
+ transform(Var.begin(),Var.end(),Var.begin(),(int(__CDECL *)(int))toupper);
+ Variables.insert(Var);
+ }
+ CLIt++;
+ }
+
+ It=Variables.begin();
+ ItEnd=Variables.end();
+ string Val;
+ while (It!=ItEnd)
+ {
+ Val+=*It;
+ Val+=";";
+ It++;
+ }
+
+ m_Variables[USED_ENVVARS]=Val;
+}
+
+static string s_TrueString("1");
+static string s_FalseString("0");
+
+static string AndExpression(const string &First, const string &Second)
+{
+ if (First.empty() || First==s_FalseString)
+ {
+ return g_EmptyString;
+ }
+ else
+ {
+ return Second.empty() || Second==s_FalseString ? g_EmptyString : s_TrueString;
+ }
+}
+
+static string OrExpression(const string &First, const string &Second)
+{
+ if (First.empty() || First==s_FalseString)
+ {
+ return Second.empty() || Second==s_FalseString ? g_EmptyString : s_TrueString;
+ }
+ else
+ {
+ return s_TrueString;
+ }
+}
+
+string mhmakefileparser::ResolveExpression(const string &InExpr,string &Rest) const
+{
+ unsigned i=0;
+ string Ret;
+ string Expr=InExpr;
+
+ Rest=g_EmptyString;
+
+ while (i<Expr.length())
+ {
+ while (strchr(" \t\r",Expr[i])) i++;
+ switch (Expr[i])
+ {
+ case '!':
+ if (i==Expr.length()-1)
+ {
+ i++; // to break out of the loop
+ Ret=s_TrueString; /* the input was ! which means true */
+ }
+ else if (Expr[i+1]!='=')
+ {
+ Ret=ResolveExpression(Expr.substr(i+1),Expr);
+ Ret = Ret.empty() || Ret==s_FalseString ? s_TrueString : g_EmptyString;
+ i=0;
+ }
+ else
+ {
+ Ret = Ret!=ResolveExpression(Expr.substr(i+2),Expr) ? s_TrueString : g_EmptyString;
+ i=0;
+ }
+ break;
+ case '&':
+ #ifdef _DEBUG
+ if (i==Expr.length()-1)
+ {
+ throw(string("Error in expression near ")+Expr[i]+": "+InExpr);
+ } else
+ #endif
+ if (Expr[i+1]!='&')
+ {
+ Ret+=Expr[i++];
+ }
+ else
+ {
+ Ret=AndExpression(Ret,ResolveExpression(Expr.substr(i+2),Expr));
+ i=0;
+ }
+ break;
+ case '|':
+ #ifdef _DEBUG
+ if (i==Expr.length()-1)
+ {
+ throw(string("Error in expression near ")+Expr[i]+": "+InExpr);
+ } else
+ #endif
+ if (Expr[i+1]!='|')
+ {
+ Ret+=Expr[i++];
+ }
+ else
+ {
+ Ret=OrExpression(Ret,ResolveExpression(Expr.substr(i+2),Expr));
+ i=0;
+ }
+ break;
+ case '(':
+ if (Ret=="defined")
+ {
+ Ret=IsDefined(ResolveExpression(Expr.substr(i+1),Expr)) ? s_TrueString : g_EmptyString;
+ }
+ else
+ {
+ Ret+=ResolveExpression(Expr.substr(i+1),Expr);
+ }
+ i=0;
+ break;
+ case ')':
+ Rest=Expr.substr(i+1);
+ return Ret;
+ break;
+ case '"':
+ {
+ i++;
+ while (i<Expr.length())
+ {
+ char Char=Expr[i++];
+ if (Char=='"')
+ break;
+ Ret+=Char;
+ }
+ }
+ break;
+ case '=':
+ if (i==Expr.length()-1)
+ {
+ i++; // To break out of the loop
+ }
+ else
+ if (Expr[i+1]!='=')
+ {
+ Ret+=Expr[i++];
+ }
+ else
+ {
+ Ret = Ret==ResolveExpression(Expr.substr(i+2),Expr) ? s_TrueString : g_EmptyString;
+ i=0;
+ }
+ break;
+ default:
+ Ret+=Expr[i++];
+ break;
+ }
+ }
+ return Ret;
+}
+///////////////////////////////////////////////////////////////////////////////
+bool mhmakefileparser::IsExprTrue(const string &EqualExpr) const
+{
+ string Expr=ExpandExpression(EqualExpr);
+ string Rest;
+ Expr=ResolveExpression(Expr,Rest);
+ if (Expr.empty() || Expr==s_FalseString)
+ return false;
+ else
+ return true;
+}
+
diff --git a/tools/mhmake/src/mhmakefileparser.h b/tools/mhmake/src/mhmakefileparser.h
new file mode 100644
index 000000000..82e783dd0
--- /dev/null
+++ b/tools/mhmake/src/mhmakefileparser.h
@@ -0,0 +1,431 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef __MHMAKEFILE_PARSER__
+#define __MHMAKEFILE_PARSER__
+
+#include "fileinfo.h"
+#include "util.h"
+#include "commandqueue.h"
+
+class rule;
+
+#include "flexlexer.h"
+
+class mhmakefileparser;
+typedef string (mhmakefileparser::*function_f)(const string &) const;
+
+struct funcdef
+{
+ const char *szFuncName;
+ function_f pFunc;
+};
+
+class fileinfoarray : public refbase,public vector<fileinfo*>
+{
+};
+
+typedef set<fileinfo*> deps_t;
+typedef pair< bool, deps_t > autodeps_entry_t;
+typedef map<fileinfo*, autodeps_entry_t > autodeps_t;
+
+namespace yy
+{
+ class location;
+ class mhmakeparser;
+}
+
+class mhmakefileparser : public refbase
+{
+ friend class yy::mhmakeparser;
+
+private:
+ static commandqueue sm_CommandQueue;
+ static stack<yy::mhmakeparser*> sm_ParserStack; // Keeps track of the currently active parser
+private:
+ fileinfo *m_RuleThatIsBuild;
+ vector<string> m_ToBeIncludeAfterBuild;
+ vector<string> m_MakefilesToLoad;
+ fileinfo* m_AutoDepFileLoaded;
+ mh_time_t m_Date;
+ uint32 m_EnvMd5_32; /* Cached Md5_32 value of the userd environment variables */
+#ifdef _DEBUG
+ int m_ImplicitSearch;
+#endif
+ map<string,string> m_CommandCache;
+
+protected:
+ map<string,string> m_Variables;
+ map<string,string> m_CommandLineVars;
+ const fileinfo *m_MakeDir;
+ refptr<rule> m_pCurrentRule;
+ refptr<fileinfoarray> m_pCurrentItems;
+ refptr<fileinfoarray> m_pCurrentDeps;
+ fileinfo* m_FirstTarget;
+ fileinfoarray m_IncludedMakefiles;
+ refptr<fileinfoarray> m_pIncludeDirs;
+ string m_IncludeDirs;
+
+ bool m_DoubleColonRule;
+ bool m_AutoDepsDirty;
+ bool m_ForceAutoDepRescan;
+ set<string> m_SkipHeaders; // Headers to skip
+ vector<string> m_PercentHeaders; // Percent specification of headers to skip
+ bool m_SkipHeadersInitialized; // true when previous 2 variables are initialized
+
+ bool m_RebuildAll; /* true when to rebuild all targets of this makefile */
+
+ set<string> m_UsedEnvVars; // Array containing a list of variables that are taken from the environment (This is used for rebuild checking)
+ set<string> m_Exports; // Array containing a list of exported variables in the makefile (This is used for rebuild checking)
+ vector< pair< string, refptr<fileinfoarray> > > m_vPath;
+#ifdef WIN32
+ char *m_pEnv; // New environment in case the makefile exports variables
+#else
+ char **m_pEnv; // New environment in case the makefile exports variables
+#endif
+ size_t m_EnvLen; // Current length of m_pEnv
+
+ autodeps_t m_AutoDeps;
+ set< const fileinfo* > m_Targets; // List of targets that are build by this makefile
+
+ vector<string> m_FilesToRemoveAtEnd;
+
+ static mh_time_t m_sBuildTime;
+private:
+ string ResolveExpression(const string &InExpr,string &Rest) const;
+
+public:
+#ifdef _DEBUG
+ deque<fileinfo*> m_TargetStack; /* Used to detect circular dependencies */
+#endif
+
+ mhmakefileparser(const map<string,string> &CommandLineVars)
+ : m_CommandLineVars(CommandLineVars)
+ ,m_AutoDepsDirty(false)
+ ,m_ForceAutoDepRescan(false)
+ ,m_SkipHeadersInitialized(false)
+ ,m_RebuildAll(false)
+ ,m_EnvMd5_32(0)
+ ,m_pEnv(NULL)
+ ,m_FirstTarget(NULL)
+ ,m_RuleThatIsBuild(NULL)
+ ,m_AutoDepFileLoaded(NULL)
+ #ifdef _DEBUG
+ ,m_ImplicitSearch(0)
+ #endif
+ {
+ if (!m_FunctionsInitialised) InitFuncs();
+ SetVariable("MAKE_VERSION",MHMAKEVER);
+ SetVariable(OBJEXTVAR,OBJEXT);
+ SetVariable(EXEEXTVAR,EXEEXT);
+ }
+
+ /* Needed if you only want to use the searchcommand and execommand functions */
+ mhmakefileparser(const fileinfo *pMakeDir) :
+ m_MakeDir(pMakeDir)
+ , m_AutoDepsDirty(false)
+ , m_pEnv(NULL)
+ {}
+
+ static void SetNrParallelBuilds(int NrParallelBuilds)
+ {
+ sm_CommandQueue.SetNrParallelBuilds(NrParallelBuilds);
+ }
+
+ bool CompareEnv() const;
+ uint32 CreateEnvMd5_32() const;
+ string GetFromEnv(const string &Var,bool Cache=true) const;
+ void CreateUSED_ENVVARS();
+
+ void SetExport(const string & Var, const string & Val);
+ void SetvPath(const string & Pattern, const string & Path);
+
+ void CheckEnv(void);
+
+ #ifdef _DEBUG
+ int ImplicitSearch() const
+ {
+ return m_ImplicitSearch;
+ }
+ #endif
+
+ void SetAutoDepsDirty()
+ {
+ m_AutoDepsDirty=true;
+ }
+
+ void ClearAutoDepsDirty()
+ {
+ m_AutoDepsDirty=false;
+ }
+ bool IsAutoDepsDirty() const
+ {
+ return m_AutoDepsDirty;
+ }
+
+ void SetRebuildAll()
+ {
+ m_RebuildAll=true;
+ SetAutoDepsDirty(); /* This is to be sure that all new calculated md5 strings are saved. */
+ }
+
+ void SetVariable(const string &Var, const string &Val)
+ {
+ m_Variables[Var]=Val;
+ }
+ void DeleteVariable(const string &Var)
+ {
+ m_Variables.erase(Var);
+ }
+ bool GetVariable(const string &Var, string &Val)
+ {
+ map<string,string>::const_iterator pIt=m_Variables.find(Var);
+ if (pIt==m_Variables.end())
+ {
+ return false;
+ }
+ else
+ {
+ Val = pIt->second;
+ return true;
+ }
+ }
+
+ void EnableAutoDepRescan(void)
+ {
+ m_ForceAutoDepRescan=true;
+ SetAutoDepsDirty();
+ }
+ bool ForceAutoDepRescan(void)
+ {
+ return m_ForceAutoDepRescan;
+ }
+ void SetRuleThatIsBuild(fileinfo *pTarget)
+ {
+ m_RuleThatIsBuild=pTarget;
+ }
+ void ClearRuleThatIsBuild()
+ {
+ m_RuleThatIsBuild=NULL;
+ }
+ void GetAutoDepsIfNeeded(fileinfo *pTarget, const fileinfo *pFirstDep);
+ void UpdateAutomaticDependencies(fileinfo *pTarget);
+ void UpdateNoRuleAutomaticDependencies(fileinfo *pTarget);
+ const refptr<fileinfoarray> GetIncludeDirs() const;
+ void GetAutoDeps(const fileinfo *pFirstDep, deps_t &Autodeps);
+ void SaveAutoDepsFile();
+ void LoadAutoDepsFile(fileinfo *pDepFile);
+ bool SkipHeaderFile(const string &FileName);
+ void InitEnv() const;
+
+ virtual ~mhmakefileparser() /* virtual to be sure the correct destructor is called when we delete with a pointer to this class which in reality is a pointer to a derived class */
+ {
+ SaveAutoDepsFile();
+ /* remove generated temporary batch files */
+ vector<string>::const_iterator It=m_FilesToRemoveAtEnd.begin();
+ while (It!=m_FilesToRemoveAtEnd.end())
+ {
+ remove(It->c_str());
+ It++;
+ }
+#ifndef WIN32
+ char **pEnv=m_pEnv;
+ if (pEnv)
+ while (*pEnv) free(*pEnv++);
+#endif
+ free(m_pEnv);
+ }
+
+ virtual int parse()
+ {
+ throw("Please derive if you want to execute yyparse.");
+ }
+
+ int ParseFile(const fileinfo *pFileInfo,const fileinfo *pMakeDir=NULL);
+ int ParseString(const string &StringIn);
+
+ /* Functions to handle variables */
+ bool IsDefined(const string &Var) const;
+ bool IsEqual(const string &EqualExpr) const;
+ bool IsExprTrue(const string &EqualExpr) const;
+ string ExpandExpression(const string &Expr) const;
+ string ExpandMacro(const string &Expr) const;
+ string ExpandVar(const string &Var) const;
+
+ void PrintVariables(bool Expand=false) const;
+
+ /* Functions for macro functions */
+ static funcdef m_FunctionsDef[];
+ static map<string,function_f> m_Functions;
+ static bool m_FunctionsInitialised;
+ static void InitFuncs(void);
+ string f_filter(const string &) const;
+ string f_call(const string &) const;
+ string f_if(const string &) const;
+ string f_findstring(const string &) const;
+ string f_firstword(const string &) const;
+ string f_wildcard(const string &) const;
+ string f_subst(const string &) const;
+ string f_patsubst(const string &) const;
+ string f_concat(const string &) const;
+ string f_basename(const string & Arg) const;
+ string f_notdir(const string & Arg) const;
+ string f_dir(const string & Arg) const;
+ string f_shell(const string & Arg) const;
+ string f_relpath(const string & Arg) const;
+ string f_toupper(const string & Arg) const;
+ string f_tolower(const string & Arg) const;
+ string f_exist(const string & Arg) const;
+ string f_filesindirs(const string & Arg) const;
+ string f_fullname(const string & Arg) const;
+ string f_addprefix(const string & Arg) const;
+ string f_addsuffix(const string & Arg) const;
+ string f_filterout(const string & Arg) const;
+ string f_word(const string & Arg) const;
+ string f_words(const string & Arg) const;
+ string f_strip(const string & Arg) const;
+ string f_which(const string & Arg) const;
+ string f_foreach(const string & Arg) const;
+ string f_eval(const string & Arg) const;
+ string f_sort(const string & Arg) const;
+ string f_error(const string & Arg) const;
+ string f_info(const string & Arg) const;
+ string f_warning(const string & Arg) const;
+
+ fileinfo* GetFirstTarget() const
+ {
+ return m_FirstTarget;
+ }
+
+ const fileinfo *GetMakeDir() const
+ {
+ return m_MakeDir;
+ }
+
+ mh_time_t GetDate(void) const
+ {
+ return m_Date;
+ }
+
+ void UpdateDate(mh_time_t Date)
+ {
+ if (Date.IsNewer(m_Date))
+ m_Date=Date;
+ }
+
+ void AddTarget(const fileinfo* pTarget)
+ {
+ m_Targets.insert(pTarget);
+ }
+ /* Starts building the target,
+ returns 0 when target build is not finished,
+ returns the date of the target when target is build, especially important for phony rules, since this will be the youngest date of all dependencies */
+ mh_time_t StartBuildTarget(fileinfo* pTarget, bool bCheckTargetDir=true);
+ /* Waits for the target being build, returns the date of the target. Not needed to be cald when StartBuildTarget returned a value different from zero */
+ mh_time_t WaitBuildTarget(fileinfo* pTarget);
+
+ fileinfo* SearchvPath(const fileinfo* pTarget); /* Search for the target using the vPath */
+
+ /* Use the following command when you want to wait for the target is built */
+ mh_time_t BuildTarget(fileinfo* pTarget, bool bCheckTargetDir=true)
+ {
+ mh_time_t TargetDate=StartBuildTarget(pTarget,bCheckTargetDir);
+ if (!TargetDate.IsDateValid())
+ TargetDate=WaitBuildTarget(pTarget);
+ return TargetDate;
+ }
+
+ void BuildDependencies(const refptr<rule> &pRule, fileinfo* pTarget, mh_time_t TargetDate, mh_time_t &YoungestDate, bool &MakeTarget);
+
+ void BuildIncludedMakefiles();
+
+ void AddIncludedMakefile(fileinfo* pMakeInfo)
+ {
+ UpdateDate(pMakeInfo->GetDate());
+ m_IncludedMakefiles.push_back(pMakeInfo);
+ }
+ fileinfoarray &GetIncludedMakefiles()
+ {
+ return m_IncludedMakefiles;
+ }
+
+ void IncludeAfterBuild(const string &IncludeFile)
+ {
+ m_ToBeIncludeAfterBuild.push_back(IncludeFile);
+ }
+ void ParseBuildedIncludeFiles();
+
+ void AddMakefileToMakefilesToLoad(const string &Makefile)
+ {
+ m_MakefilesToLoad.push_back(Makefile);
+ }
+ vector<string>& GetMakefilesToLoad()
+ {
+ return m_MakefilesToLoad;
+ }
+ void AddRule();
+
+ mh_pid_t ExecuteCommand(string Command, bool &IgnoreError, string *pOutput=NULL);
+ mh_pid_t ExecuteCommand(string Command, string *pOutput=NULL)
+ {
+ bool IgnoreError;
+ return ExecuteCommand(Command, IgnoreError, pOutput);
+ }
+ string GetFullCommand(const string &Command);
+
+ static void InitBuildTime();
+
+ void SplitToItems(const string &String, vector<fileinfo*> &Items) const;
+ mh_pid_t DeleteFiles(const string &Params) const;
+ mh_pid_t CopyFiles(const string &Params) const;
+ mh_pid_t TouchFiles(const string &Params) const;
+ mh_pid_t EchoCommand(const string &Params) const;
+ mh_pid_t MakeDirsCommand(const string &Params) const;
+ string SearchCommand(const string &Command, const string &Extension="") const;
+ const string &GetPythonExe() const;
+ int SearchPath(const char *szCommand, const char *pExt, size_t Len, char *szFullCommand,char **pFilePart) const;
+ mh_pid_t OsExeCommand(const string &Command, const string &Params, bool IgnoreError, string *pOutput) const;
+
+ static string GetFileNameLineNo(void);
+};
+
+class mhmakeparserbase
+{
+protected:
+ mhmakefileparser *m_pMakefile;
+ mhmakeFlexLexer *m_ptheLexer;
+public:
+ mhmakeparserbase(mhmakefileparser *pMakefile, mhmakeFlexLexer *pLexer)
+ : m_pMakefile(pMakefile), m_ptheLexer(pLexer)
+ {
+ }
+ int yylex (YYSTYPE* yylval, yy::location* yylloc)
+ {
+ return m_ptheLexer->yylex(yylval,yylloc);
+ }
+ string &GetInputFilename(void) const
+ {
+ return m_ptheLexer->GetInputFilename();
+ }
+
+};
+
+#endif
+
diff --git a/tools/mhmake/src/mhmakelexer.l b/tools/mhmake/src/mhmakelexer.l
new file mode 100644
index 000000000..aa396ceaf
--- /dev/null
+++ b/tools/mhmake/src/mhmakelexer.l
@@ -0,0 +1,922 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+/* -------------- declaration section -------------- */
+%{
+
+#include "fileinfo.h"
+#include "rule.h"
+#include "util.h"
+
+static uint32 LoadMakMd5(fileinfo *pTarget)
+{
+ uint32 Md5_32=0;
+ string FileName=pTarget->GetFullFileName();
+ FileName+=".md5_32";
+ FILE *pFile=fopen(FileName.c_str(),"rb");
+ if (!pFile)
+ return Md5_32;
+ if (1!=fread(&Md5_32,sizeof(Md5_32),1,pFile))
+ {
+ fclose(pFile);
+ return Md5_32;
+ }
+ pTarget->SetCommandsMd5_32(Md5_32);
+ fclose(pFile);
+ return Md5_32;
+}
+
+static void SaveMakMd5(fileinfo *pTarget)
+{
+ string FileName=pTarget->GetFullFileName();
+ FileName+=".md5_32";
+ FILE *pFile=fopen(FileName.c_str(),"wb");
+ if (!pFile)
+ {
+ throw string("Error creating file ")+FileName;
+ }
+ pTarget->WriteMd5_32(pFile);
+ fclose(pFile);
+}
+
+static void ReplaceCurlyBraces(string &String)
+{
+ int Pos=String.find_first_of('{',0);
+ if (Pos!=string::npos)
+ {
+ /* if not { found, } will not be there eather (or it is a valid syntax, so it may generate an error) */
+ do
+ {
+ String.replace(Pos,1,1,'(');
+ Pos=String.find_first_of('{',Pos);
+ }
+ while (Pos!=string::npos);
+ Pos=0;
+ while ((Pos=String.find_first_of('}',Pos))!=string::npos)
+ String.replace(Pos,1,1,')');
+ }
+}
+
+#include "mhmakeparser.hpp"
+
+#define YY_DECL int mhmakeFlexLexer::yylex(yy::mhmakeparser::semantic_type* yylval, yy::mhmakeparser::location_type* yylloc)
+
+/* By default yylex returns int, we use token_type.
+ Unfortunately yyterminate by default returns 0, which is
+ not of token_type. */
+#define yyterminate() return yy::mhmakeparser::token::END
+
+%}
+
+%option prefix="mhmake"
+%option never-interactive
+%option 8bit
+%option c++
+%option full
+%option noyywrap
+%option warn
+
+/* -------------- rules section -------------- */
+%x INCLUDE IFDEF IF IFNDEF SKIPUNTILELSEORENDIF QUOTE MAKEEXPRES SINGLEQUOTE COMMANDPARSE
+%x IFEQ IFNEQ LOAD_MAKEFILE
+%x DEFINE
+
+%{
+# define YY_USER_ACTION yylloc->columns (yyleng);
+
+#define inclineno() yylloc->incline()
+#define lineno() yylloc->end.line
+#define colno() yylloc->end.column
+
+
+%}
+%%
+%{
+ yylloc->step ();
+%}
+
+ /*---------------------------------------------------------------------------*/
+[ \t\r]*\n[ ][ \t]* {
+ yy_set_bol(1); // Make sure the next rule also matches the ^
+ inclineno();
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+[ \t\r]*\n {
+ PRINTF(("%s %d: NEWLINE:\n",m_InputFileName.c_str(),lineno()));
+ inclineno();
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+^[s\-]?include {
+ PRINTF(("%s %d: INCLUDE: ",m_InputFileName.c_str(),lineno()));
+ BEGIN(INCLUDE);
+ unsigned i=0;
+ while (strchr(" \t",yytext[i])) i++;
+ if (strchr("-s",yytext[i]))
+ m_IgnoreIncludeError=true;
+ else
+ m_IgnoreIncludeError=false;
+ return yy::mhmakeparser::token::INCLUDEMAK; // Return a newline to be sure that the previous line is completely parse by yacc (in case it is a variable definition)
+}
+
+ /*****************************************************************************/
+<INCLUDE>[ \t]* /* eat the whitespace */
+ /*---------------------------------------------------------------------------*/
+<INCLUDE>[^\r\n]+ { /* got the include file name */
+ mhmakefileparser *pParser=GetParser();
+
+ /* replace the {} by () before expanding */
+ string IncludeFileNames(yytext);
+ ReplaceCurlyBraces(IncludeFileNames);
+ IncludeFileNames=pParser->ExpandExpression(IncludeFileNames);
+ PRINTF(("%s -> %s\n",yytext,IncludeFileNames.c_str()));
+
+ const char *pTmp=IncludeFileNames.c_str();
+ while (*pTmp)
+ {
+ string IncludeFileName;
+ pTmp=NextItem(pTmp,IncludeFileName);
+ if (!IncludeFileName.empty())
+ {
+ PRINTF(("%s -> %s\n",yytext,IncludeFileName.c_str()));
+ fileinfo *pInclude=GetFileInfo(IncludeFileName,pParser->GetMakeDir());
+ /* Already build the include file, in case we already have a rule for it. */
+ if (pInclude->GetRule())
+ {
+ uint32 Md5_32=LoadMakMd5(pInclude);
+ pParser->BuildTarget(pInclude);
+ if (!pInclude->CompareMd5_32(Md5_32))
+ SaveMakMd5(pInclude);
+ }
+
+ pParser->AddIncludedMakefile(pInclude);
+
+ string strToInclude=pInclude->GetFullFileName();
+ INSTACK *pStackElem=new INSTACK(YY_CURRENT_BUFFER, strToInclude, m_InputFileName, yylloc);
+ if ( pStackElem->fail() )
+ {
+ delete pStackElem;
+ if (!m_IgnoreIncludeError)
+ {
+ mystack::reverse_iterator StackIt=m_IncludeStack.rbegin();
+ while (StackIt!=m_IncludeStack.rend())
+ {
+ cout<<" in "<<(*StackIt)->m_FileName<<" ("<<(*StackIt)->yylloc<<")";
+ StackIt++;
+ }
+ cout<<endl;
+ cout<<"Warning error opening file "<<strToInclude<<" in "<<m_InputFileName<<" ("<<lineno()<<")\n";
+ pParser->IncludeAfterBuild(strToInclude);
+ }
+ else
+ pInclude->SetPhony(); /* To be sure that no message is printed when mhmake is trying to build the file later */
+ }
+ else
+ {
+ m_IncludeStack.push(pStackElem);
+
+ m_InputFileName=strToInclude;
+ yylloc->initialize(&m_InputFileName);
+
+ yypush_buffer_state(yy_create_buffer( pStackElem->GetStream(), YY_BUF_SIZE ));
+ yyrestart(pStackElem->GetStream());
+ }
+
+ }
+ }
+
+ BEGIN(INITIAL);
+}
+
+ /*---------------------------------------------------------------------------*/
+load_makefile {
+ PRINTF(("%s %d: LOAD_MAKEFILE:\n",m_InputFileName.c_str(),lineno()));
+ BEGIN(LOAD_MAKEFILE);
+ return yy::mhmakeparser::token::NEWLINE; // Return a newline to be sure that the previous line is completely parse by yacc (in case it is a variable definition)
+}
+
+ /*****************************************************************************/
+<LOAD_MAKEFILE>[^\r\n]+ {
+ string ListOfMakefiles((const char*)yytext);
+ ReplaceCurlyBraces(ListOfMakefiles);
+ ListOfMakefiles=GetParser()->ExpandExpression(ListOfMakefiles);
+ PRINTF(("%s %d: LOAD_MAKEFILE: '%s'\n",m_InputFileName.c_str(),lineno(),ListOfMakefiles.c_str()));
+
+ const char *pTmp=ListOfMakefiles.c_str();
+ while (*pTmp)
+ {
+ string Item;
+ pTmp=NextCharItem(pTmp,Item,';');
+ if (Item.empty())
+ {
+ throw m_InputFileName + "(" + stringify(lineno()) + "): Error in load_makefile statement";
+ }
+ GetParser()->AddMakefileToMakefilesToLoad(Item);
+ }
+
+}
+ /*---------------------------------------------------------------------------*/
+<LOAD_MAKEFILE>\r?\n {
+ inclineno();
+ BEGIN(INITIAL);
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]+ {
+ PRINTF(("%s %d: SPACE:\n",m_InputFileName.c_str(),lineno()));
+ return yy::mhmakeparser::token::SPACE;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*=[ \t]*\\[ \t\r]*\n[ \t]* {
+ PRINTF(("%s %d: EQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ inclineno();
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::EQUAL;
+}
+
+[ \t]*=[ \t]* {
+ PRINTF(("%s %d: EQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::EQUAL;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*:=[ \t]*\\[ \t\r]*\n[ \t]* {
+ inclineno();
+ PRINTF(("%s %d: IMEQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::IMEQUAL;
+}
+
+[ \t]*:=[ \t]* {
+ PRINTF(("%s %d: IMEQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::IMEQUAL;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*\?=[ \t]*\\[ \t\r]*\n[ \t]* {
+ inclineno();
+ PRINTF(("%s %d: OPTEQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::OPTEQUAL;
+}
+
+[ \t]*\?=[ \t]* {
+ PRINTF(("%s %d: OPTEQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::OPTEQUAL;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*\+=[ \t]*\\[ \t\r]*\n[ \t]* {
+ PRINTF(("%s %d: PEQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ inclineno();
+ return yy::mhmakeparser::token::PEQUAL;
+}
+
+[ \t]*\+=[ \t]* {
+ PRINTF(("%s %d: PEQUAL: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::PEQUAL;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*;[ \t]*\\[ \t\r]*\n[ \t]* {
+ PRINTF(("%s %d: -SEMICOLON (NEWLINE): %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ m_curtoken=g_EmptyString;
+ inclineno();
+ BEGIN(COMMANDPARSE);
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+[ \t]*;[ \t]* {
+ PRINTF(("%s %d: -SEMICOLON (NEWLINE): %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ m_curtoken=g_EmptyString;
+ BEGIN(COMMANDPARSE);
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*::[ \t]*\\[ \t\r]*\n[ \t]* {
+ PRINTF(("%s %d: DOUBLECOLON: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ inclineno();
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::DOUBLECOLON;
+}
+
+[ \t]*::[ \t]* {
+ PRINTF(("%s %d: DOUBLECOLON: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::DOUBLECOLON;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*:[ \t]*\\[ \t\r]*\n[ \t]* {
+ PRINTF(("%s %d: COLON: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ inclineno();
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::COLON;
+}
+
+[ \t]*:[ \t]* {
+ PRINTF(("%s %d: COLON: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::COLON;
+}
+
+ /*---------------------------------------------------------------------------*/
+, {
+ PRINTF(("%s %d: COMMA: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::COMMA;
+}
+
+ /*---------------------------------------------------------------------------*/
+^endif {
+ if (m_IndentStack.size())
+ {
+ m_IndentStack.pop();
+ PRINTF(("%s %d: %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext,m_IndentStack.size()));
+ }
+ else
+ {
+ throw string("Unexpected endif at line ") + stringify(lineno()) + " of " + m_InputFileName;
+ }
+}
+
+ /*---------------------------------------------------------------------------*/
+^ifdef[ \t]*\\[ \t\r]*\n[ \t]* {
+ BEGIN(IFDEF);
+ inclineno();
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+^ifdef[ \t]+ {
+ BEGIN(IFDEF);
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+^if[ \t]*\\[ \t\r]*\n[ \t]* {
+ BEGIN(IF);
+ inclineno();
+ m_curtoken=g_EmptyString;
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+^if[ \t]+ {
+ BEGIN(IF);
+ m_curtoken=g_EmptyString;
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+^ifndef[ \t]*\\[ \t\r]*\n[ \t]* {
+ BEGIN(IFNDEF);
+ inclineno();
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+^ifndef[ \t]+ {
+ BEGIN(IFNDEF);
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+^ifeq[ \t]*\\[ \t\r]*\n[ \t]* {
+ BEGIN(IFEQ);
+ m_curtoken=g_EmptyString;
+ inclineno();
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+^ifeq[ \t]+ {
+ BEGIN(IFEQ);
+ m_curtoken=g_EmptyString;
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+^ifneq[ \t]*\\[ \t\r]*\n[ \t]* {
+ BEGIN(IFNEQ);
+ m_curtoken=g_EmptyString;
+ inclineno();
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+^ifneq[ \t]+ {
+ BEGIN(IFNEQ);
+ m_curtoken=g_EmptyString;
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+^else[ \t]* {
+ if (m_IndentStack.size() && (!m_IndentStack.top()))
+ {
+ PRINTF(("%s %d: skipping else: depth %d\n",m_InputFileName.c_str(),lineno(),m_IndentStack.size()));
+ m_IndentSkip=m_IndentStack.size();
+ m_IndentStack.top()=1;
+ BEGIN(SKIPUNTILELSEORENDIF);
+ }
+ else
+ {
+ throw string("Unexpected else at line ") + stringify(lineno()) + " of file " + m_InputFileName;
+ }
+}
+
+ /*****************************************************************************/
+<IFEQ>\n {
+ yyless(0);
+ m_IndentStack.push(0);
+ if (GetParser()->IsEqual(m_curtoken))
+ {
+ PRINTF(("%s %d: Not Skipping ifeq %s: depth %d\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str(),m_IndentStack.size()));
+ BEGIN(INITIAL);
+ }
+ else
+ {
+ PRINTF(("%s %d: Skipping ifeq %s: depth %d\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str(),m_IndentStack.size()));
+ m_IndentSkip=m_IndentStack.size();
+ BEGIN(SKIPUNTILELSEORENDIF);
+ }
+}
+
+<IF,IFEQ,IFNEQ>[ \t]*\\[ \t\r]*\n[ \t]* { inclineno(); m_curtoken += g_SpaceString;}
+
+<IF,IFEQ,IFNEQ>\r /* skip */
+
+<IF,IFEQ,IFNEQ>[^\\\r\n\$#]+ |
+<IF,IFEQ,IFNEQ>[\\\$] { m_curtoken += (const char *)yytext; }
+
+ /*****************************************************************************/
+<IFNEQ>\n {
+ yyless(0);
+ m_IndentStack.push(0);
+ if (!GetParser()->IsEqual(m_curtoken))
+ {
+ PRINTF(("%s %d: Not Skipping ifneq %s: depth %d\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str(),m_IndentStack.size()));
+ BEGIN(INITIAL);
+ }
+ else
+ {
+ PRINTF(("%s %d: Skipping ifneq %s: depth %d\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str(),m_IndentStack.size()));
+ m_IndentSkip=m_IndentStack.size();
+ BEGIN(SKIPUNTILELSEORENDIF);
+ }
+}
+
+ /*****************************************************************************/
+<IF>[ \t\r]*[a-zA-Z0-9_]+[ \t\r]*\n {
+ yyless(yyleng-1);
+ m_IndentStack.push(0);
+#ifndef WIN32
+ int lastidx=yyleng-1;
+ if (yytext[lastidx]=='\r')
+ yytext[lastidx]='\0';
+#endif
+ string Val=GetParser()->ExpandVar((const char *)yytext);
+ if (Val.empty() || Val=="0")
+ {
+ PRINTF(("%s %d: Skipping if %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext,m_IndentStack.size()));
+ m_IndentSkip=m_IndentStack.size();
+ BEGIN(SKIPUNTILELSEORENDIF);
+ }
+ else
+ {
+ PRINTF(("%s %d: Not Skipping if %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext,m_IndentStack.size()));
+ BEGIN(INITIAL);
+ }
+}
+
+ /*---------------------------------------------------------------------------*/
+<IF>\n {
+ yyless(0);
+ m_IndentStack.push(0);
+ if (GetParser()->IsExprTrue(m_curtoken))
+ {
+ PRINTF(("%s %d: Not Skipping ifeq %s: depth %d\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str(),m_IndentStack.size()));
+ BEGIN(INITIAL);
+ }
+ else
+ {
+ PRINTF(("%s %d: Skipping ifeq %s: depth %d\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str(),m_IndentStack.size()));
+ m_IndentSkip=m_IndentStack.size();
+ BEGIN(SKIPUNTILELSEORENDIF);
+ }
+}
+
+ /*****************************************************************************/
+<IFDEF,IFNDEF>[ \t\r]* /* skip */
+
+ /*---------------------------------------------------------------------------*/
+<IFDEF>[a-zA-Z0-9_]+ {
+ m_IndentStack.push(0);
+ if (GetParser()->IsDefined((const char *)yytext))
+ {
+ PRINTF(("%s %d: Not Skipping ifdef %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext,m_IndentStack.size()));
+ BEGIN(INITIAL);
+ }
+ else
+ {
+ PRINTF(("%s %d: Skipping ifdef %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext,m_IndentStack.size()));
+ m_IndentSkip=m_IndentStack.size();
+ BEGIN(SKIPUNTILELSEORENDIF);
+ }
+}
+
+ /*****************************************************************************/
+<IFNDEF>[a-zA-Z0-9_]+ {
+ m_IndentStack.push(0);
+ if (!GetParser()->IsDefined((const char *)yytext)) {
+ PRINTF(("%s %d: Not Skipping ifndef %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext,m_IndentStack.size()));
+ BEGIN(INITIAL);
+ }
+ else
+ {
+ PRINTF(("%s %d: Skipping ifndef %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext,m_IndentStack.size()));
+ m_IndentSkip=m_IndentStack.size();
+ BEGIN(SKIPUNTILELSEORENDIF);
+ }
+}
+
+ /*****************************************************************************/
+<SKIPUNTILELSEORENDIF>\n[ ]*endif {
+ inclineno();
+ if (!m_IndentStack.size())
+ {
+ throw string("Unexpected endif at line ") + stringify(lineno()) + " of " + m_InputFileName;
+ }
+ else
+ {
+ m_IndentStack.pop();
+ PRINTF(("%s %d: endif: depth %d\n",m_InputFileName.c_str(),lineno(),m_IndentStack.size()));
+ if (m_IndentStack.size()==m_IndentSkip-1) BEGIN(INITIAL);
+ }
+}
+
+ /*---------------------------------------------------------------------------*/
+<SKIPUNTILELSEORENDIF>\n[ ]*else {
+ inclineno();
+ PRINTF(("%s %d: else: depth %d\n",m_InputFileName.c_str(),lineno(),m_IndentStack.size()));
+ if (m_IndentStack.top())
+ {
+ throw string("Unexpected else at line ") + stringify(lineno()) + " of file " + m_InputFileName;
+ }
+ m_IndentStack.top()=1;
+ if (m_IndentStack.size()==m_IndentSkip)
+ {
+ BEGIN(INITIAL);
+ }
+}
+
+ /*---------------------------------------------------------------------------*/
+<SKIPUNTILELSEORENDIF>\n[ ]*if(def|ndef|eq|neq)? {
+ inclineno();
+ m_IndentStack.push(0);
+ PRINTF(("%s %d: %s: depth %d\n",m_InputFileName.c_str(),lineno(),yytext+1,m_IndentStack.size()));
+}
+
+ /*---------------------------------------------------------------------------*/
+<SKIPUNTILELSEORENDIF>[a-zA-Z]+ /* skip */
+ /*---------------------------------------------------------------------------*/
+<SKIPUNTILELSEORENDIF>[^a-zA-Z\n]+ /* skip */
+ /*---------------------------------------------------------------------------*/
+<SKIPUNTILELSEORENDIF>\n[ ]*[a-zA-Z]+ {
+ inclineno();
+}
+ /*---------------------------------------------------------------------------*/
+<SKIPUNTILELSEORENDIF>\n {
+ inclineno();
+}
+
+ /*---------------------------------------------------------------------------*/
+<INITIAL,COMMANDPARSE,IF,IFEQ,IFNEQ>[ \t]*#[^\n]* {
+ PRINTF(("%s %d: -COMMENT: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t]*\\[ \t\r]*\n[ \t]* {
+ PRINTF(("%s %d: SPACE:\n",m_InputFileName.c_str(),lineno()));
+ inclineno();
+ return yy::mhmakeparser::token::SPACE;
+}
+
+ /*---------------------------------------------------------------------------*/
+\.PHONY {
+ PRINTF(("%s %d: .PHONY: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::PHONY;
+}
+
+ /*---------------------------------------------------------------------------*/
+\.AUTODEPS {
+ PRINTF(("%s %d: .AUTODEPS: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::AUTODEPS;
+}
+
+ /*---------------------------------------------------------------------------*/
+export {
+ PRINTF(("%s %d: export: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ return yy::mhmakeparser::token::EXPORT;
+}
+
+ /*---------------------------------------------------------------------------*/
+^vpath {
+ PRINTF(("%s %d: vpath\n",m_InputFileName.c_str(),lineno()));
+ return yy::mhmakeparser::token::VPATH;
+}
+
+ /*---------------------------------------------------------------------------*/
+[a-zA-Z]:[a-zA-Z0-9\\\._\~\-%\@<&/]+\\[ \t\r]*\n {
+ size_t EndIndex=yyleng;
+ while (strchr(" \t\r\n\\",yytext[--EndIndex]));
+ yyless(EndIndex+1);
+
+ PRINTF(("%s %d: STRING: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+[a-zA-Z]:[a-zA-Z0-9\\\._\~\-%\@<&/]+ {
+ PRINTF(("%s %d: STRING: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+ /*---------------------------------------------------------------------------*/
+([a-zA-Z0-9\\\._\~\-\+%\@<&;/\*\|]|\\\ |\\#)+\\[ \t\r]*\n {
+ size_t EndIndex=yyleng;
+ while (strchr(" \t\r\n\\",yytext[--EndIndex]));
+ yyless(EndIndex+1);
+
+ PRINTF(("%s %d: STRING: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+([a-zA-Z0-9\\\._\~\-\+%\@<&;/\*\|]|\\\ |\\#)+\+= {
+ PRINTF(("%s %d: STRING: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yyless(yyleng-2);
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+([a-zA-Z0-9\\\._\~\-\+%\@<&;/\*\|\[\]]|\\\ |\\#)+ {
+ PRINTF(("%s %d: STRING: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+^define[ \t]+[a-zA-Z0-9_\.]+[ \t]*\n {
+ const char *pVar=(const char *)yytext;
+ while (strchr(" \t",*pVar)) pVar++;
+ pVar+=6;
+ yylval->theString=pVar;
+ BEGIN(DEFINE);
+ m_curtoken=g_EmptyString;
+ PRINTF(("%s %d: VARDEF: %s\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str()));
+ inclineno();
+ return yy::mhmakeparser::token::VARDEF;
+}
+
+<DEFINE>[ \t]*\\[ \t\r]*\n[ \t]* {
+ inclineno();
+ m_curtoken+=g_SpaceString;
+}
+
+<DEFINE>\n {
+ inclineno();
+ m_curtoken+=(const char *)yytext;
+}
+
+<DEFINE>. {
+ m_curtoken+=(const char *)yytext;
+}
+
+<DEFINE>[ \t]*\n[ \t]*endef {
+ inclineno();
+ yylval->theString=m_curtoken;
+ PRINTF(("%s %d: VARVAL: %s\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str()));
+ BEGIN(INITIAL);
+ return yy::mhmakeparser::token::VARVAL;
+}
+
+ /*---------------------------------------------------------------------------*/
+\" {
+ BEGIN(QUOTE);
+ yymore();
+}
+
+ /*---------------------------------------------------------------------------*/
+\' {
+ BEGIN(SINGLEQUOTE);
+ yymore();
+}
+
+ /*---------------------------------------------------------------------------*/
+\$[\(\{] {
+ m_BraceIndent++;
+ PRINTF(("%s %d: BEGIN MACRO $(: %d\n",m_InputFileName.c_str(),lineno(),m_BraceIndent));
+ BEGIN(MAKEEXPRES);
+ m_curtoken=(const char *)yytext;
+}
+
+ /*---------------------------------------------------------------------------*/
+\$[<@/$] {
+ PRINTF(("%s %d: DOLLAREXPR: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::DOLLAREXPR;
+}
+
+ /*---------------------------------------------------------------------------*/
+[ \t\r]*\n\t[ \t]* {
+ /* token newline */
+ PRINTF(("%s %d: NEWLINE\n",m_InputFileName.c_str(),lineno()));
+ inclineno();
+ m_curtoken=g_EmptyString;
+ BEGIN(COMMANDPARSE);
+ return yy::mhmakeparser::token::NEWLINE;
+}
+
+ /*---------------------------------------------------------------------------*/
+[\(\)\{\}] {
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+ /*---------------------------------------------------------------------------*/
+[^\n] {
+ PRINTF(("%s %d: ANYCHAR: %d: %s\n",m_InputFileName.c_str(),lineno(),lineno(),yytext));
+ throw string("Unexpected character '")+yytext+"' in makefile '" + m_InputFileName + "' at line "+stringify(lineno()) + ", column " + stringify(colno()-1);
+}
+
+ /*****************************************************************************/
+
+<COMMANDPARSE>[ \t\r]*\n {
+ PRINTF(("%s %d: COMMAND: %d: %s\n",m_InputFileName.c_str(),lineno(),lineno(),m_curtoken.c_str()));
+ yylval->theString=m_curtoken;
+ inclineno();
+ BEGIN(INITIAL);
+ return yy::mhmakeparser::token::COMMAND;
+}
+
+ /*---------------------------------------------------------------------------*/
+<COMMANDPARSE>[ \t\r]*\n\t[ \t]* {
+ PRINTF(("%s %d: COMMAND: %s\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str()));
+ yylval->theString=m_curtoken;
+ inclineno();
+ m_curtoken=g_EmptyString;
+ return yy::mhmakeparser::token::COMMAND;
+}
+
+ /*---------------------------------------------------------------------------*/
+<COMMANDPARSE>[ \t]*\\[ \t\r]*\n[ \t]* {
+ inclineno();
+ m_curtoken+=g_SpaceString;
+}
+
+ /*---------------------------------------------------------------------------*/
+<COMMANDPARSE>[ ]+ {
+ m_curtoken+=g_SpaceString;
+}
+
+ /*---------------------------------------------------------------------------*/
+<COMMANDPARSE>[^ \r\n#\\$]+ |
+<COMMANDPARSE>[\\\$] {
+ m_curtoken+=(const char *)yytext;
+}
+
+ /*---------------------------------------------------------------------------*/
+<COMMANDPARSE>[ \t]*\\#[^\n]* {
+ int nChars=(int)((strchr((const char *)yytext,'#')-(char*)yytext))+1;
+ yyless(nChars);
+ m_curtoken+=string(yytext,nChars-2);
+ m_curtoken+='#';
+}
+
+ /*****************************************************************************/
+<QUOTE>\" {
+ PRINTF(("%s %d: QUOTEDSTRING: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ BEGIN(INITIAL);
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+ /*---------------------------------------------------------------------------*/
+<QUOTE>\r /* skip */
+
+<QUOTE>[^\\\"\r\n$]+ |
+<QUOTE>[\\\$] |
+<QUOTE>\\\" |
+<QUOTE>\\# {
+ yymore();
+}
+
+ /*****************************************************************************/
+<SINGLEQUOTE>\' {
+ PRINTF(("%s %d: QUOTEDSTRING: %s\n",m_InputFileName.c_str(),lineno(),yytext));
+ BEGIN(INITIAL);
+ yylval->theString=(const char *)yytext;
+ return yy::mhmakeparser::token::STRING;
+}
+
+ /*---------------------------------------------------------------------------*/
+<SINGLEQUOTE>\r /* skip */
+
+<SINGLEQUOTE>[^\\\'\r\n$]+ |
+<SINGLEQUOTE>[\\\$] |
+<SINGLEQUOTE>\\\' |
+<SINGLEQUOTE>\\# {
+ yymore();
+}
+
+ /*****************************************************************************/
+<MAKEEXPRES>[\)\}] {
+ m_BraceIndent--;
+ PRINTF(("%s %d: CLOSE BRACE MAKEEXPRES MACRO ): %d\n",m_InputFileName.c_str(),lineno(),m_BraceIndent));
+ if (!m_BraceIndent)
+ {
+ BEGIN(INITIAL);
+ m_curtoken+=(const char *)yytext;
+ yylval->theString=m_curtoken;
+ PRINTF(("%s %d: DOLLAREXPR: %s\n",m_InputFileName.c_str(),lineno(),m_curtoken.c_str()));
+ return yy::mhmakeparser::token::DOLLAREXPR;
+ }
+ else
+ {
+ m_curtoken+=(const char *)yytext;
+ }
+}
+
+ /*---------------------------------------------------------------------------*/
+<MAKEEXPRES>\$[\(\{] {
+ m_BraceIndent++;
+ PRINTF(("%s %d: MACRO extra $(: %d\n",m_InputFileName.c_str(),lineno(),m_BraceIndent));
+ m_curtoken+=(const char *)yytext;
+}
+
+ /*---------------------------------------------------------------------------*/
+<MAKEEXPRES>[\(\{] {
+ m_BraceIndent++;
+ m_curtoken+=(const char *)yytext;
+}
+
+ /*---------------------------------------------------------------------------*/
+<MAKEEXPRES>[^$\(\)\{\}\r\n\\]+ |
+<MAKEEXPRES>[\(\$\\\{] {
+ m_curtoken+=(const char *)yytext;
+}
+<MAKEEXPRES>[ \t\r]*\\[ \t\r]*\n[ \t\r]* {
+ inclineno();
+ m_curtoken+=g_SpaceString;
+}
+
+<MAKEEXPRES>\n {
+ throw m_InputFileName + "(" + stringify(lineno()) + "): End of line inside macro is not allowed";
+}
+
+<SKIPUNTILELSEORENDIF><<EOF>> {
+ throw string("Missing endif or else statement. #else or #endif used?");
+}
+
+<<EOF>> {
+ if (m_BraceIndent)
+ {
+ throw string("Missing closing ) or } of macro usage in ") + m_InputFileName;
+ }
+ if (!m_IncludeStack.size())
+ {
+ if (m_IndentStack.size())
+ {
+ throw string("Missing endif or else statement in ") + m_InputFileName + ". #else or #endif used";
+ }
+ yyterminate();
+ }
+ else
+ {
+ INSTACK *pInStack=m_IncludeStack.top();
+ yypop_buffer_state();
+ m_InputFileName=pInStack->m_FileName;
+ *yylloc=pInStack->yylloc;
+ m_IncludeStack.pop();
+ }
+}
+%%
+
diff --git a/tools/mhmake/src/mhmakeparser.y b/tools/mhmake/src/mhmakeparser.y
new file mode 100644
index 000000000..847cda48a
--- /dev/null
+++ b/tools/mhmake/src/mhmakeparser.y
@@ -0,0 +1,284 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+/* -------------- declaration section -------------- */
+
+%require "2.4.1"
+%defines
+%define parser_class_name "mhmakeparser"
+%define parser_base_class_name "mhmakeparserbase"
+%define parser_class_constructor_init ": mhmakeparserbase(pMakefile,pLexer)"
+%define parser_class_constructor_param "mhmakefileparser *pMakefile, mhmakeFlexLexer *pLexer"
+%error-verbose
+
+%code requires {
+#include "mhmakefileparser.h"
+}
+
+%code provides {
+const char Test[]="dit is een test";
+}
+
+%{
+#include "mhmakefileparser.h"
+#include "rule.h"
+#include "util.h"
+%}
+
+%locations
+%initial-action
+{
+ // Initialize the initial location.
+ @$.initialize(&m_ptheLexer->GetInputFilename());
+};
+
+%token END 0 "end of file"
+%token <theString> COMMAND
+%token <theString> COMMA
+%token <theString> STRING DOLLAREXPR EQUAL COLON DOUBLECOLON VARDEF VARVAL
+%token IMEQUAL PEQUAL OPTEQUAL PHONY AUTODEPS EXPORT NEWLINE INCLUDEMAK SPACE VPATH
+
+%type <theString> expression nonspaceexpression simpleexpression
+%type <theString> maybeemptyexpression
+%type <theString> expression_nocolorequal simpleexpression_nocolorequal nonspaceexpression_nocolorequal
+%type <ival> rulecolon
+
+%start file
+
+/* -------------- rules section -------------- */
+/* Sample parser. Does count Chars in a line, and lines in file */
+%%
+file : statements
+ {
+ if (m_pMakefile->m_pCurrentItems)
+ {
+ PRINTF(("Adding rule : %s\n",(*m_pMakefile->m_pCurrentItems)[0]->GetQuotedFullFileName().c_str()));
+ m_pMakefile->AddRule();
+ }
+ }
+;
+
+statements :
+ | statements statement
+;
+
+space : SPACE |
+ space SPACE
+;
+
+statement: NEWLINE |
+ SPACE |
+ DOLLAREXPR NEWLINE {
+ m_pMakefile->ExpandExpression($1);
+ } |
+ includemak |
+ ruledef |
+ phonyrule |
+ autodepsrule |
+ varassignment |
+ imvarassignment |
+ pvarassignment |
+ optvarassignment |
+ exportrule |
+ vpathrule |
+ COMMAND
+ {
+ if (!m_pMakefile->m_pCurrentRule)
+ {
+ m_pMakefile->m_pCurrentRule=refptr<rule>(new rule(m_pMakefile));
+ }
+ m_pMakefile->m_pCurrentRule->AddCommand($1);
+ PRINTF(("Adding command : %s\n",$1.c_str()));
+ }
+;
+
+includemak:
+ {
+ if (m_pMakefile->m_pCurrentItems)
+ {
+ PRINTF(("Adding rule : %s\n",(*m_pMakefile->m_pCurrentItems)[0]->GetQuotedFullFileName().c_str()));
+ m_pMakefile->AddRule();
+ }
+ } INCLUDEMAK
+;
+
+ruledef: expression_nocolorequal rulecolon maybeemptyexpression
+ {
+ if (m_pMakefile->m_pCurrentItems)
+ {
+ PRINTF(("Adding rule : %s\n",(*m_pMakefile->m_pCurrentItems)[0]->GetQuotedFullFileName().c_str()));
+ m_pMakefile->AddRule();
+ }
+
+ m_pMakefile->m_pCurrentItems=new fileinfoarray;
+ m_pMakefile->m_pCurrentDeps=new fileinfoarray;
+ #ifdef _DEBUG
+ if (!m_pMakefile->ExpandExpression($1).size())
+ {
+ throw string("Empty left hand side in rule: ") + $1 + " : " + $3;
+ }
+ #endif
+ m_pMakefile->SplitToItems(m_pMakefile->ExpandExpression($1),*m_pMakefile->m_pCurrentItems);
+ m_pMakefile->SplitToItems(m_pMakefile->ExpandExpression($3),*m_pMakefile->m_pCurrentDeps);
+ m_pMakefile->m_DoubleColonRule= ($2==1) ;
+ PRINTF(("Defining rule %s : %s\n",$1.c_str(),$3.c_str()));
+ PRINTF((" Expanded to %s : %s\n",m_pMakefile->ExpandExpression($1).c_str(),m_pMakefile->ExpandExpression($3).c_str()));
+ }
+;
+
+rulecolon: COLON {$$=0;} |
+ DOUBLECOLON {$$=1;}
+;
+
+phonyrule: PHONY COLON expression
+ {
+ vector<fileinfo*> Items;
+ m_pMakefile->SplitToItems(m_pMakefile->ExpandExpression($3),Items);
+ vector<fileinfo*>::iterator pIt=Items.begin();
+ while (pIt!=Items.end())
+ {
+ (*pIt)->SetPhony();
+ pIt++;
+ }
+ PRINTF(("Defining phony rule : %s\n",$3.c_str()));
+ PRINTF((" Expanded to : %s\n",m_pMakefile->ExpandExpression($3).c_str()));
+ }
+ NEWLINE
+;
+
+autodepsrule: AUTODEPS COLON expression
+ {
+ vector<fileinfo*> Items;
+ m_pMakefile->SplitToItems(m_pMakefile->ExpandExpression($3),Items);
+ vector<fileinfo*>::iterator pIt=Items.begin();
+ while (pIt!=Items.end())
+ {
+ (*pIt)->SetAutoDepsScan(m_pMakefile);
+ pIt++;
+ }
+ PRINTF(("Defining autodeps rule : %s\n",$3.c_str()));
+ PRINTF((" Expanded to : %s\n",m_pMakefile->ExpandExpression($3).c_str()));
+ }
+ NEWLINE
+;
+
+exportrule: EXPORT space exportstrings NEWLINE |
+ EXPORT space STRING EQUAL maybeemptyexpression
+ {
+ string Val=m_pMakefile->ExpandExpression($5);
+ m_pMakefile->SetVariable($3,Val);
+ m_pMakefile->SetExport($3,Val);
+ PRINTF(("Exporting %s : %s\n",$3.c_str(), Val.c_str()));
+ }
+;
+
+exportstrings : exportstring |
+ exportstring space exportstrings
+;
+
+exportstring : STRING
+ {
+ m_pMakefile->SetExport($1,m_pMakefile->ExpandExpression(m_pMakefile->ExpandVar($1)));
+ PRINTF(("Exporting %s : %s\n",$1.c_str(),m_pMakefile->ExpandExpression(m_pMakefile->ExpandVar($1)).c_str()));
+ }
+;
+
+vpathrule: VPATH space nonspaceexpression space expression NEWLINE
+ {
+ m_pMakefile->SetvPath(m_pMakefile->ExpandExpression($3),m_pMakefile->ExpandExpression($5));
+ PRINTF(("Setting vpath %s to %s\n",$3.c_str(),m_pMakefile->ExpandExpression($5).c_str()));
+ }
+;
+
+varassignment: VARDEF VARVAL
+ {
+ m_pMakefile->m_Variables[m_pMakefile->f_strip($1)]=$2;
+ PRINTF(("Defining variable %s to %s\n",m_pMakefile->f_strip($1).c_str(), $2.c_str()));
+ }
+ | STRING EQUAL maybeemptyexpression
+ {
+ m_pMakefile->m_Variables[$1]=$3;
+ PRINTF(("Setting variable %s to %s\n",$1.c_str(), $3.c_str()));
+ }
+;
+
+imvarassignment: STRING IMEQUAL maybeemptyexpression
+ {
+ m_pMakefile->m_Variables[$1]=m_pMakefile->ExpandExpression($3);
+ PRINTF(("Setting variable %s to %s\n",$1.c_str(), m_pMakefile->m_Variables[$1].c_str()));
+ }
+;
+
+pvarassignment: STRING PEQUAL maybeemptyexpression
+ {
+ m_pMakefile->m_Variables[$1]=m_pMakefile->ExpandVar($1)+g_SpaceString+$3;
+ PRINTF(("Adding to variable %s: %s\n",$1.c_str(), $3.c_str()));
+ }
+;
+
+optvarassignment: STRING OPTEQUAL maybeemptyexpression
+ {
+ if (!m_pMakefile->IsDefined($1))
+ {
+ m_pMakefile->m_Variables[$1]=$3;
+ PRINTF(("Setting variable %s to %s\n",$1.c_str(), $3.c_str()));
+ }
+ }
+;
+
+maybeemptyexpression: NEWLINE {$$=g_EmptyString;} |
+ expression NEWLINE |
+ expression space NEWLINE
+;
+
+expression: nonspaceexpression |
+ expression space nonspaceexpression {$$=$1+g_SpaceString+$3;}
+;
+
+expression_nocolorequal: nonspaceexpression_nocolorequal |
+ expression_nocolorequal space nonspaceexpression_nocolorequal {$$=$1+g_SpaceString+$3;}
+;
+
+nonspaceexpression: simpleexpression |
+ nonspaceexpression simpleexpression {$$=$1+$2;}
+;
+
+nonspaceexpression_nocolorequal: simpleexpression_nocolorequal |
+ nonspaceexpression_nocolorequal simpleexpression_nocolorequal {$$=$1+$2;}
+;
+
+simpleexpression: simpleexpression_nocolorequal |
+ EQUAL |
+ COLON |
+ DOUBLECOLON |
+ COMMA
+;
+
+simpleexpression_nocolorequal: STRING |
+ DOLLAREXPR
+;
+
+%%
+/* -------------- body section -------------- */
+
+void yy::mhmakeparser::error (const yy::mhmakeparser::location_type& l, const std::string& m)
+{
+ cerr << l << " -> "<<m<<endl;
+}
diff --git a/tools/mhmake/src/refptr.h b/tools/mhmake/src/refptr.h
new file mode 100644
index 000000000..7223090f9
--- /dev/null
+++ b/tools/mhmake/src/refptr.h
@@ -0,0 +1,124 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef __REFPTR_H__
+#define __REFPTR_H__
+
+#ifdef _DEBUG
+#define PRINTF(arg) if (g_PrintLexYacc) printf arg
+#else
+#define PRINTF(arg)
+#endif
+
+template <class T> class iterstack: public stack<T>
+{
+ public:
+ typedef typename deque<T>::iterator iterator;
+ typedef typename deque<T>::reverse_iterator reverse_iterator;
+
+ iterator begin()
+ {
+ return stack<T>::c.begin();
+ }
+ iterator end()
+ {
+ return stack<T>::c.end();
+ }
+ reverse_iterator rbegin()
+ {
+ return stack<T>::c.rbegin();
+ }
+ reverse_iterator rend()
+ {
+ return stack<T>::c.rend();
+ }
+};
+
+struct refbase
+{
+ int m_Count;
+ refbase()
+ {
+ m_Count=1;
+ }
+};
+
+// Template class T needs to be derived from refbase;
+template <class T> class refptr
+{
+ T *m_RefPtr;
+public:
+ refptr()
+ {
+ m_RefPtr=NULL;
+ }
+ refptr(T *Ptr) {
+ m_RefPtr=Ptr;
+ }
+ refptr(const refptr<T> &RefPtr)
+ {
+ m_RefPtr=RefPtr.m_RefPtr;
+ if (m_RefPtr)
+ m_RefPtr->m_Count++;
+ }
+ ~refptr()
+ {
+ if (m_RefPtr && !--m_RefPtr->m_Count)
+ {
+ delete m_RefPtr;
+ }
+ }
+ refptr<T> &operator=(const refptr<T>& Src)
+ {
+ if (Src.m_RefPtr!=m_RefPtr)
+ {
+ this->~refptr();
+ new (this) refptr<T>(Src);
+ }
+ return *this;
+ }
+
+ refptr<T> &operator=(T *pPtr) // Assumes that T has reference count 1 and has no other users
+ {
+ #if defined(_DEBUG) && defined(_MSC_VER)
+ if (pPtr && pPtr->m_Count!=1)
+ DebugBreak();
+ #endif
+ this->~refptr();
+ m_RefPtr=pPtr;
+ return *this;
+ }
+
+ T & operator*() const
+ {
+ return *m_RefPtr;
+ }
+ T * operator->() const
+ {
+ return m_RefPtr;
+ }
+ operator T*() const
+ {
+ return m_RefPtr;
+ }
+};
+
+#endif
+
diff --git a/tools/mhmake/src/rule.cpp b/tools/mhmake/src/rule.cpp
new file mode 100644
index 000000000..35884e2f0
--- /dev/null
+++ b/tools/mhmake/src/rule.cpp
@@ -0,0 +1,301 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+
+#include "fileinfo.h"
+#include "rule.h"
+#include "util.h"
+#include "mhmakefileparser.h"
+
+refptr<rule> NullRule;
+
+set<rule*> IMPLICITRULE::m_ImplicitRuleRecurseDetStack;
+vector<implicitrule_t> IMPLICITRULE::m_ImplicitRules;
+
+makecommand g_MakeCommand; // Order is important since sm_Statics is using g_MakeCommand
+const string g_QuoteString("\""); // Order is important since sm_Statics is using g_QuoteString
+loadedmakefile::loadedmakefile_statics loadedmakefile::sm_Statics;
+
+///////////////////////////////////////////////////////////////////////////////
+static bool FindDep(fileinfo *pTarget, implicitruledep_t *pImplicitRule,refptr<rule> &Rule)
+{
+ implicitruledep_t::iterator SecIt=pImplicitRule->begin();
+ while (SecIt!=pImplicitRule->end())
+ {
+ if (SecIt->first.empty())
+ {
+ #ifdef _DEBUG
+ // Check if the rule has the same commands
+ vector<string> &OldCommands=SecIt->second->GetCommands();
+ vector<string> &NewCommands=Rule->GetCommands();
+
+ bool bCommandsDifferent=OldCommands.size()!=NewCommands.size();
+ if (g_PrintMultipleDefinedRules || bCommandsDifferent)
+ {
+ string ErrorMessage;
+ if (bCommandsDifferent)
+ ErrorMessage += "Implicit Rule '"+ pTarget->GetFullFileName() + "' defined twice with different commands\n";
+ else
+ ErrorMessage += "Implicit Rule '"+ pTarget->GetFullFileName() + "' defined twice with same commands\n";
+ ErrorMessage += "Command 1: makedir = " + SecIt->second->GetMakefile()->GetMakeDir()->GetQuotedFullFileName()+ "\n";
+
+ vector<string>::const_iterator It;
+ if (bCommandsDifferent)
+ {
+ It=OldCommands.begin();
+ while (It!=OldCommands.end())
+ {
+ ErrorMessage += " " + *It + "\n";
+ }
+ }
+ cerr << "Command 2: makedir = "+ Rule->GetMakefile()->GetMakeDir()->GetQuotedFullFileName()+ "\n";
+ if (bCommandsDifferent)
+ {
+ It=NewCommands.begin();
+ while (It!=NewCommands.end())
+ {
+ ErrorMessage += " " + *It + "\n";
+ }
+ throw ErrorMessage;
+ }
+ else
+ cerr << ErrorMessage << endl;
+ }
+ mhmakefileparser *pOldMakefile=SecIt->second->GetMakefile();
+ mhmakefileparser *pNewMakefile=Rule->GetMakefile();
+ vector<string>::iterator OldIt=OldCommands.begin();
+ vector<string>::iterator NewIt=NewCommands.begin();
+ while (OldIt!=OldCommands.end())
+ {
+ if (pOldMakefile->ExpandExpression(*OldIt)!=pNewMakefile->ExpandExpression(*NewIt))
+ {
+ string ErrorMessage = string("Implicit Rule '") + pTarget->GetFullFileName() + "' defined twice with different commands\n";
+ ErrorMessage += "Command 1: makedir = " + pOldMakefile->GetMakeDir()->GetQuotedFullFileName()+ "\n";
+ ErrorMessage += " " + pOldMakefile->ExpandExpression(*OldIt) + "\n";
+ ErrorMessage += "Command 2: makedir = " + pNewMakefile->GetMakeDir()->GetQuotedFullFileName()+ "\n";
+ ErrorMessage += " " + pNewMakefile->ExpandExpression(*NewIt);
+ throw ErrorMessage;
+ }
+ OldIt++;
+ NewIt++;
+ }
+ #endif
+ return true;
+ }
+ SecIt++;
+ }
+ return false;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void IMPLICITRULE::AddImplicitRule(fileinfo *pTarget,const vector<fileinfo*> &Deps,refptr<rule> Rule)
+{
+ if (!Rule)
+ {
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "No commands defined for implicit rule " << pTarget->GetFullFileName()<<endl;
+ #endif
+ return;
+ }
+ // first search if there is already the same target in the current list of implicit rules
+ implicitruledep_t* pImplicitRule=NULL;
+ vector<implicitrule_t>::iterator RuleIt=m_ImplicitRules.begin();
+ while (RuleIt!=m_ImplicitRules.end())
+ {
+ if (pTarget==RuleIt->first)
+ {
+ pImplicitRule=&(RuleIt->second);
+ }
+ RuleIt++;
+ }
+ if (!pImplicitRule)
+ {
+ // Add a new entry
+ m_ImplicitRules.push_back(implicitrule_t(pTarget,implicitruledep_t()));
+ pImplicitRule=&((m_ImplicitRules.end()-1)->second);
+ }
+
+ if (Deps.size())
+ {
+ #ifdef _DEBUG
+ vector<fileinfo*>::const_iterator DepIt=Deps.begin();
+ while (DepIt!=Deps.end())
+ {
+ if (*DepIt==pTarget)
+ throw(string("Implicit rule : ")+pTarget->GetFullFileName()+" is directly dependent on itself. This is not allowed.");
+ DepIt++;
+ }
+ #endif
+ pImplicitRule->push_back(pair<vector<fileinfo*>,refptr<rule> >(Deps,Rule));
+ }
+ else
+ {
+ if (!FindDep(pTarget,pImplicitRule,Rule))
+ pImplicitRule->push_back(pair<vector<fileinfo*>, refptr<rule> >(vector<fileinfo*>(), Rule));
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void IMPLICITRULE::SearchImplicitRule(const fileinfo *pTarget, implicitruledep_t &Result)
+{
+ string TargetFileName=pTarget->GetFullFileName();
+
+ vector<implicitrule_t>::iterator ImpRegExIt=m_ImplicitRules.begin();
+ while (ImpRegExIt!=m_ImplicitRules.end())
+ {
+ matchres Res;
+
+ if (PercentMatch(TargetFileName,ImpRegExIt->first->GetFullFileName(),&Res))
+ {
+ implicitruledep_t::iterator ResIt=ImpRegExIt->second.begin();
+ while (ResIt!=ImpRegExIt->second.end())
+ {
+#ifdef _DEBUG
+ if (!ResIt->second)
+ {
+ throw string("No commands for implicit rule : ") + ImpRegExIt->first->GetFullFileName();
+ }
+#endif
+ ResIt->second->SetStem(Res.m_Stem);
+ vector<fileinfo*> Deps;
+ const fileinfo *pMakeDir=ResIt->second->GetMakefile()->GetMakeDir();
+ vector<fileinfo*>::iterator It=ResIt->first.begin();
+ while (It!=ResIt->first.end())
+ {
+ string Dependent=ReplaceWithStem((*It)->GetFullFileName(),Res.m_Stem);
+ #ifdef _DEBUG
+ if (Dependent.length()>MAX_PATH)
+ {
+ /* File name is getting too long, this is most probable an infinit loop */
+ throw(string("Filename too long in implicit rule search: ")+Dependent+"\nProbably some infinit loop in the implicit rules search.\n");
+ }
+ #endif
+ Deps.push_back(GetFileInfo(Dependent,pMakeDir));
+ It++;
+ }
+ Result.push_back(pair<vector<fileinfo*>,refptr<rule> >(Deps, ResIt->second));
+ ResIt++;
+ }
+ }
+ ImpRegExIt++;
+ }
+ return;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+bool rule::operator != (const rule &Other)
+{
+ if (m_Commands.size()!=Other.m_Commands.size())
+ return true;
+
+ vector<string>::const_iterator It=m_Commands.begin();
+ vector<string>::const_iterator OtherIt=Other.m_Commands.begin();
+ while (It!=m_Commands.end())
+ {
+ if (m_pMakefile->ExpandExpression(*It)!=Other.m_pMakefile->ExpandExpression(*OtherIt))
+ return true;
+ It++;
+ OtherIt++;
+ }
+ return false;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void rule::SetTargetsIsBuild(uint32 Md5_32)
+{
+ vector< fileinfo* >::iterator It=m_Targets.begin();
+ while (It!=m_Targets.end())
+ {
+ (*It)->SetCommandsMd5_32(Md5_32);
+ (*It)->SetBuild();
+ m_pMakefile->AddTarget(*It);
+ It++;
+ }
+}
+///////////////////////////////////////////////////////////////////////////////
+void rule::SetTargetsIsBuilding(const fileinfo *pSrc)
+{
+ vector< fileinfo* >::iterator It=m_Targets.begin();
+ while (It!=m_Targets.end())
+ {
+ if ((*It)!=pSrc)
+ (*It)->SetBuilding(false);
+ It++;
+ }
+}
+
+
+#ifdef _DEBUG
+///////////////////////////////////////////////////////////////////////////////
+void IMPLICITRULE::PrintImplicitRules()
+{
+ vector<implicitrule_t>::iterator ImpRegExIt=m_ImplicitRules.begin();
+ while (ImpRegExIt!=m_ImplicitRules.end())
+ {
+ implicitruledep_t::iterator SecIt=ImpRegExIt->second.begin();
+ cout << ImpRegExIt->first->GetFullFileName() << " :\n";
+ while (SecIt!=ImpRegExIt->second.end())
+ {
+ cout << " :";
+ vector<fileinfo*>::iterator DepIt=SecIt->first.begin();
+ while (DepIt!=SecIt->first.end())
+ {
+ cout << " " << (*DepIt)->GetQuotedFullFileName() <<endl;
+ DepIt++;
+ }
+ cout << endl;
+ if (SecIt->second)
+ {
+ SecIt->second->PrintCommands();
+ }
+ else
+ {
+ cout << " No rhs\n";
+ }
+ SecIt++;
+ }
+ ImpRegExIt++;
+ }
+ return;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void rule::PrintCommands(fileinfo *pTarget) const
+{
+ if (pTarget)
+ m_pMakefile->SetRuleThatIsBuild(pTarget);
+
+ vector<string>::const_iterator pCommandIt=m_Commands.begin();
+ while (pCommandIt!=m_Commands.end())
+ {
+ cout<<g_SpaceString<<*pCommandIt<<endl;
+ if (pTarget)
+ {
+ cout<<" ("<<m_pMakefile->ExpandExpression(*pCommandIt)<<")\n";
+ }
+ pCommandIt++;
+ }
+}
+
+#endif
+
+
diff --git a/tools/mhmake/src/rule.h b/tools/mhmake/src/rule.h
new file mode 100644
index 000000000..7cc287600
--- /dev/null
+++ b/tools/mhmake/src/rule.h
@@ -0,0 +1,110 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef __RULE_H__
+#define __RULE_H__
+
+#include "refptr.h"
+#include "md5.h"
+class mhmakefileparser;
+class fileinfo;
+
+class rule: public refbase
+{
+ vector<string> m_Commands;
+ string m_Stem; // Contains the stem in case the rule is part of an implicit rule (filled in in the implicit search)
+ mhmakefileparser* m_pMakefile;
+ vector< fileinfo* > m_Targets; /* Targets that are build with this rule, do not use refptr here because otherwise we get circular references */
+public:
+ rule(mhmakefileparser *pMakefile): m_pMakefile(pMakefile)
+ {
+ }
+
+ void AddCommand(const string &Command)
+ {
+ if (!Command.empty())
+ m_Commands.push_back(Command);
+ }
+ vector<string>& GetCommands()
+ {
+ return m_Commands;
+ }
+ void PrintCommands(fileinfo *pTarget=NULL) const;
+
+ void SetStem(const string &Stem)
+ {
+ m_Stem=Stem;
+ }
+ const string &GetStem() const
+ {
+ return m_Stem;
+ }
+ void SetMakefile(mhmakefileparser *pMakefile)
+ {
+ m_pMakefile=pMakefile;
+ }
+ mhmakefileparser *GetMakefile()
+ {
+ return m_pMakefile;
+ }
+ bool operator != (const rule &Rule);
+
+ void AddTarget(fileinfo *pTarget)
+ {
+ m_Targets.push_back(pTarget);
+ }
+ void SetTargetsIsBuild(uint32 Md5_32);
+ void SetTargetsIsBuilding(const fileinfo *pSrc);
+};
+
+typedef vector<pair<vector<fileinfo*>,refptr<rule> > > implicitruledep_t;
+typedef pair<fileinfo *, implicitruledep_t > implicitrule_t;
+
+class IMPLICITRULE
+{
+ static set<rule*> m_ImplicitRuleRecurseDetStack;
+ static vector<implicitrule_t> m_ImplicitRules; // Use a vector and not a map because the order of the implicit rules is important
+public:
+ static void AddImplicitRule(fileinfo *pTarget,const vector<fileinfo*> &Deps, refptr<rule> pRule);
+ static void SearchImplicitRule(const fileinfo *pTarget, implicitruledep_t &Result);
+ static void PrintImplicitRules();
+ static bool PushRule(rule *pRule)
+ {
+ set<rule*>::iterator pFound=m_ImplicitRuleRecurseDetStack.find(pRule);
+ if (pFound==m_ImplicitRuleRecurseDetStack.end())
+ {
+ m_ImplicitRuleRecurseDetStack.insert(pRule);
+ return false;
+ }
+ else
+ {
+ return true;
+ }
+ }
+ static void PopRule(rule *pRule)
+ {
+ m_ImplicitRuleRecurseDetStack.erase(pRule);
+ }
+};
+
+extern refptr<rule> NullRule;
+
+#endif
+
diff --git a/tools/mhmake/src/stdafx.cpp b/tools/mhmake/src/stdafx.cpp
new file mode 100644
index 000000000..b2168250b
--- /dev/null
+++ b/tools/mhmake/src/stdafx.cpp
@@ -0,0 +1,24 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+// This file is only used to generate the pre-compiled header files. The stdafx.h file
+// should only contain includes of headers that will not be likely to change (like system header files)
+
+#include "stdafx.h"
diff --git a/tools/mhmake/src/stdafx.h b/tools/mhmake/src/stdafx.h
new file mode 100644
index 000000000..e586ebb6b
--- /dev/null
+++ b/tools/mhmake/src/stdafx.h
@@ -0,0 +1,92 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+// stdafx.h : include file for standard system include files,
+// or project specific include files that are used frequently, but
+// are changed infrequently
+//
+
+#if !defined(AFX_STDAFX_H__CDC9F92E_2B83_4EFC_92B5_44861521ED45__INCLUDED_)
+#define AFX_STDAFX_H__CDC9F92E_2B83_4EFC_92B5_44861521ED45__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#pragma warning (disable:4786)
+#pragma warning (disable:4503)
+#pragma warning (disable:4530)
+#endif // _MSC_VER > 1000
+
+#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
+
+#include <iostream>
+#include <fstream>
+#include <string>
+#include <vector>
+#include <queue>
+#include <map>
+#include <set>
+#include <stack>
+#include <algorithm>
+#include <sstream>
+
+#ifdef _MSC_VER
+#include <io.h>
+#define __CDECL __cdecl
+#else
+#define __CDECL
+#define _stricmp strcasecmp
+#define _strnicmp strncasecmp
+#define MAX_PATH 255
+#include <sys/wait.h>
+#include <popt.h>
+#include <glob.h>
+#endif
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <malloc.h>
+#ifdef _MSC_VER
+#include <crtdbg.h>
+#endif
+#include <string.h>
+#ifdef _MSC_VER
+#include <direct.h>
+#define mkdir(name,mode) _mkdir(name)
+#endif
+#include <time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef WIN32
+#include <windows.h>
+#ifdef max
+#undef max
+#endif
+#ifdef min
+#undef min
+#endif
+#endif
+
+using namespace std;
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_STDAFX_H__CDC9F92E_2B83_4EFC_92B5_44861521ED45__INCLUDED_)
+
diff --git a/tools/mhmake/src/util.cpp b/tools/mhmake/src/util.cpp
new file mode 100644
index 000000000..3e20706dd
--- /dev/null
+++ b/tools/mhmake/src/util.cpp
@@ -0,0 +1,812 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#include "stdafx.h"
+
+#include "rule.h"
+#include "util.h"
+#include "mhmakeparser.hpp"
+
+#ifdef WIN32
+
+#include <WinIoCtl.h>
+
+#define REPARSE_MOUNTPOINT_HEADER_SIZE 8
+
+typedef struct {
+ DWORD ReparseTag;
+ DWORD ReparseDataLength;
+ WORD Reserved;
+ WORD ReparseTargetLength;
+ WORD ReparseTargetMaximumLength;
+ WORD Reserved1;
+ WCHAR ReparseTarget[1];
+} REPARSE_MOUNTPOINT_DATA_BUFFER, *PREPARSE_MOUNTPOINT_DATA_BUFFER;
+#endif
+
+static char s_UsageString[]=
+"\
+Usage: mhmake [-f <Makefile>] [-[c|C] <RunDir>] [<Var>=<Value>]\n\
+ [-a] [-q] [-s] [-S] [-v] [-P <Nr Parallel Builds>] [targets]+\n"
+#ifdef _DEBUG
+"\
+ [-p] [-n] [-e] [-l] [-w] [-d] [-CD] [-m] [-b]\n"
+#endif
+"\n\
+ <Makefile> : Makefile to load (if not specified 'makefile' is used\n\
+ <RunDir> : Make is setting the current directory to this directory at the\n\
+ start.\n\
+ <Var> : Defines a variable\n\
+ <Value> : Value of the variable\n\
+ -a : Rebuild all targets\n\
+ -s : Rescan automatic dependencies\n\
+ -S : SKip checking if mhmake is started in a subdirectory of the\n\
+ %MHMAKECONF dir \n\
+ -v : Print version information\n\
+ -q : Quiet. Disable all output \n\
+ -P <Nr Parallel Builds> :\n\
+ Number of parallel build commands executed at the \n\
+ same time. Default is this the number of processor \n\
+ cores. 1 disables parallel builds.\n"
+#ifdef _DEBUG
+"\n\
+ The following options are additional options in mhmake_dbg which are not\n\
+ available in mhmake. These are mainly options for debugging purposes.\n\
+ -e : Dump Vars and Rules on error\n\
+ -w : Print additional information\n\
+ -p : Prints the variables and the rules before building\n\
+ -n : Only prints the commands, but does not execute them\n\
+ -l : Print parser debug information\n\
+ -d : Print the dependency checking\n\
+ -CD : Do circular dependency checking (targets depending on itself)\n\
+ -m : Create md5 database in md5.database in start directory. \n\
+ -b : Print build tree. \n\
+ -D : Print all double defined rules (even if commands are the same) \n\
+"
+#else
+"\
+\n\
+It is adviced during creation of makefiles to use mhmake_dbg. It has additional\n\
+debugging options and does some extra error checking.\n\
+For a description of the additional options: run mhmake_dbg -h\n\
+"
+#endif
+;
+
+#ifdef _DEBUG
+bool g_PrintVarsAndRules=false;
+bool g_DoNotExecute=false;
+bool g_BuildMd5Db=false;
+bool g_GenProjectTree=false;
+bool g_DumpOnError=false;
+bool g_PrintAdditionalInfo=false;
+bool g_pPrintDependencyCheck=false;
+bool g_CheckCircularDeps=false;
+bool g_PrintLexYacc=false;
+bool g_PrintMultipleDefinedRules=false;
+#endif
+
+bool g_Quiet=false;
+bool g_RebuildAll=false;
+bool g_ForceAutoDepRescan=false;
+bool g_SkipMhMakeConfDirCheck=false;
+
+const string g_EmptyString;
+const string g_SpaceString(" ");
+
+///////////////////////////////////////////////////////////////////////////////
+void PrintVersionInfo(void)
+{
+ static const char VersionStr[]="\
+mhmake : GNU compatible make tool with extensions\n\
+version: "MHMAKEVER"\n\
+Remarks and bug reports -> marha@sourceforge.net\n\
+";
+ cerr << VersionStr;
+ exit(1);
+}
+///////////////////////////////////////////////////////////////////////////////
+makecommand::makecommand()
+{
+ char ExeName[MAX_PATH];
+#ifdef WIN32
+ GetModuleFileName(NULL,ExeName,sizeof(ExeName));
+ m_BuildCommand=ExeName;
+ transform(m_BuildCommand.begin(),m_BuildCommand.end(),m_BuildCommand.begin(),(int(__CDECL *)(int))tolower);
+#else
+ int NrChars=readlink ("/proc/self/exe", ExeName, sizeof(ExeName));
+ ExeName[NrChars]=0;
+ m_BuildCommand=ExeName;
+#endif
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string Substitute(const string &ToSubst,const string &iSrcStr,const string &iToStr)
+{
+ string Ret=g_EmptyString;
+ matchres Res;
+ string SrcStr=iSrcStr;
+ string ToStr=iToStr;
+
+ if (string::npos==SrcStr.find('%'))
+ {
+ string PerStr("%");
+ SrcStr=PerStr+SrcStr;
+ ToStr=PerStr+ToStr;
+ }
+ const char *pTmp=ToSubst.c_str();
+ bool first=true;
+ while (*pTmp)
+ {
+ if (!first)
+ {
+ Ret+=g_SpaceString;
+ }
+ else
+ {
+ first=false;
+ }
+ string Item;
+ pTmp=NextItem(pTmp,Item);
+
+ if (PercentMatch(Item,SrcStr,&Res))
+ {
+ Ret+=ReplaceWithStem(ToStr,Res.m_Stem);
+ }
+ else
+ {
+ Ret+=Item;
+ }
+ }
+
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+bool PercentMatch(const string &String,const string &Expr,matchres *pRes,const char Char)
+{
+ const char *pFirst=String.c_str();
+ const char *pFirstExpr=Expr.c_str();
+ while (*pFirstExpr && *pFirstExpr!=Char)
+ {
+ if (*pFirst!=*pFirstExpr)
+ return false;
+ pFirst++;
+ pFirstExpr++;
+ }
+
+ if (!*pFirstExpr)
+ {
+ if (!*pFirst)
+ {
+ if (pRes)
+ {
+ pRes->m_First=String;
+ pRes->m_Stem=pRes->m_Last=g_EmptyString;
+ }
+ return true;
+ } else
+ return false;
+ }
+ else if (!*pFirst)
+ return false;
+
+ const char *pEnd=pFirst+strlen(pFirst);
+
+ const char *pLast=pEnd;
+ const char *pLastExpr=pFirstExpr+strlen(pFirstExpr)-1;
+ if (pLastExpr!=pFirstExpr)
+ {
+ pLast--;
+
+ while (pLastExpr>pFirstExpr)
+ {
+ if (*pLastExpr!=*pLast)
+ return false;
+ pLastExpr--;
+ pLast--;
+ }
+ pLast++;
+ }
+ string Stem=string(pFirst,pLast-pFirst);
+
+ if (pRes)
+ {
+ pRes->m_First=string(String.c_str(),pFirst-String.c_str());
+
+ pRes->m_Stem=Stem;
+
+ pRes->m_Last=string(pLast,pEnd-pLast);
+ }
+ return true;
+}
+///////////////////////////////////////////////////////////////////////////////
+bool PercentMatchNoCase(const string &String,const string &Expr,matchres *pRes,const char Char)
+{
+ const char *pFirst=String.c_str();
+ const char *pFirstExpr=Expr.c_str();
+ while (*pFirstExpr && *pFirstExpr!=Char)
+ {
+ if (tolower(*pFirst)!=tolower(*pFirstExpr))
+ return false;
+ pFirst++;
+ pFirstExpr++;
+ }
+
+ if (!*pFirstExpr)
+ {
+ if (!*pFirst)
+ {
+ if (pRes)
+ {
+ pRes->m_First=String;
+ pRes->m_Stem=pRes->m_Last=g_EmptyString;
+ }
+ return true;
+ } else
+ return false;
+ }
+ else if (!*pFirst)
+ return false;
+
+ const char *pEnd=pFirst+strlen(pFirst);
+
+ const char *pLast=pEnd;
+ const char *pLastExpr=pFirstExpr+strlen(pFirstExpr)-1;
+ if (pLastExpr!=pFirstExpr)
+ {
+ pLast--;
+
+ while (pLastExpr>pFirstExpr)
+ {
+ if (tolower(*pLastExpr)!=tolower(*pLast))
+ return false;
+ pLastExpr--;
+ pLast--;
+ }
+ pLast++;
+ }
+ string Stem=string(pFirst,pLast-pFirst);
+
+ if (pRes)
+ {
+ pRes->m_First=string(String.c_str(),pFirst-String.c_str());
+
+ pRes->m_Stem=Stem;
+
+ pRes->m_Last=string(pLast,pEnd-pLast);
+ }
+ return true;
+}
+///////////////////////////////////////////////////////////////////////////////
+bool PercentMatchList(const string &String,const string &ExprList,matchres *pRes)
+{
+ const char *pTmp=ExprList.c_str();
+ while (*pTmp)
+ {
+ string Expr;
+ pTmp=NextItem(pTmp,Expr);
+ if (PercentMatch(String,Expr,pRes))
+ return true;
+ }
+ return false;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+string ReplaceWithStem(const string &String,const string &Stem)
+{
+ string Ret=String;
+ size_t Pos=Ret.find('%');
+ while (Pos!=string::npos)
+ {
+ Ret=Ret.substr(0,Pos)+Stem+Ret.substr(Pos+1);
+ Pos=Ret.find('%');
+ }
+ return Ret;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+refptr<loadedmakefile> LOADEDMAKEFILES::find(const loadedmakefile &ToSearch)
+{
+ vector<refptr<loadedmakefile> >::const_iterator It=begin();
+ while (It!=end())
+ {
+ if (*(*It)==ToSearch)
+ return *It;
+ It++;
+ }
+ return refptr<loadedmakefile>();
+}
+
+LOADEDMAKEFILES g_LoadedMakefiles;
+
+///////////////////////////////////////////////////////////////////////////////
+loadedmakefile::loadedmakefile_statics::loadedmakefile_statics()
+{
+ m_GlobalCommandLineVars[MAKE]=g_MakeCommand;
+ const char *pEnv=getenv(MHMAKECONF);
+ if (pEnv)
+ {
+ m_MhMakeConf=GetAbsFileInfo(pEnv);
+ m_GlobalCommandLineVars[MHMAKECONF]=QuoteFileName(m_MhMakeConf->GetFullFileName());
+
+ // Get the revision of the working copy
+ // We do it with the svn info command
+
+ string Output;
+ try
+ {
+ mhmakefileparser Dummy(curdir::GetCurDir());
+ string SvnCommand=Dummy.SearchCommand("svn",EXEEXT);
+ #ifdef WIN32
+ if (GetFileAttributes(m_MhMakeConf->GetFullFileName().c_str())&FILE_ATTRIBUTE_REPARSE_POINT)
+ {
+ WIN32_FIND_DATA FindData;
+ HANDLE hFind=FindFirstFile(m_MhMakeConf->GetFullFileName().c_str(),&FindData);
+ if (hFind!=INVALID_HANDLE_VALUE)
+ {
+ if (FindData.dwReserved0==IO_REPARSE_TAG_MOUNT_POINT)
+ {
+ HANDLE hDir = ::CreateFile(m_MhMakeConf->GetFullFileName().c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
+
+ BYTE buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; // We need a large buffer
+ REPARSE_MOUNTPOINT_DATA_BUFFER& ReparseBuffer = (REPARSE_MOUNTPOINT_DATA_BUFFER&)buf;
+ DWORD dwRet;
+
+ if (::DeviceIoControl(hDir, FSCTL_GET_REPARSE_POINT, NULL, 0, &ReparseBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dwRet, NULL))
+ {
+ // Success
+ ::CloseHandle(hDir);
+
+ LPCWSTR pPath = ReparseBuffer.ReparseTarget;
+ if (wcsncmp(pPath, L"\\??\\", 4) == 0) pPath += 4; // Skip 'non-parsed' prefix
+ char szPath[MAX_PATH];
+ ::WideCharToMultiByte(CP_ACP, 0, pPath, -1, szPath, MAX_PATH, NULL, NULL);
+ Dummy.OsExeCommand(SvnCommand,string(" info ")+GetFileInfo(szPath,m_MhMakeConf->GetDir())->GetQuotedFullFileName(),false,&Output);
+ }
+ else
+ { // Error
+ ::CloseHandle(hDir);
+ }
+ }
+ FindClose(hFind);
+ }
+ }
+ #else
+ struct stat Stat;
+ lstat(m_MhMakeConf->GetFullFileName().c_str(),&Stat);
+ if (S_ISLNK(Stat.st_mode))
+ {
+ char FileName[1024];
+ int len=readlink(m_MhMakeConf->GetFullFileName().c_str(),FileName,sizeof(FileName));
+ FileName[len]=0;
+ Dummy.OsExeCommand(SvnCommand,string(" info ")+GetFileInfo(FileName,m_MhMakeConf->GetDir())->GetQuotedFullFileName(),false,&Output);
+ }
+ #endif
+ else
+ Dummy.OsExeCommand(SvnCommand,string(" info ")+m_MhMakeConf->GetQuotedFullFileName(),false,&Output);
+ }
+ catch (string Message)
+ {
+ }
+
+ char *pTok=strtok((char*)Output.c_str(),"\n"); // doing this is changing string, so this is very dangerous !!!
+ while (pTok)
+ {
+ if (!strncmp(pTok,"URL: ",5))
+ {
+ m_GlobalCommandLineVars[WC_URL]=pTok+5+7;
+ }
+ else if (!strncmp(pTok,"Revision: ",10))
+ {
+ m_GlobalCommandLineVars[WC_REVISION]=pTok+10;
+ break;
+ }
+ pTok=strtok(NULL,"\n");
+ }
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+loadedmakefile::loadedmakefile(const fileinfo *pDir, vector<string> &Args,const string&Makefile)
+{
+ m_Makefile=NULL;
+ m_CommandLineVars=sm_Statics.m_GlobalCommandLineVars;
+
+ m_MakeDir=NULL;
+ vector<string>::iterator ArgIt=Args.begin();
+ while (ArgIt!=Args.end())
+ {
+ size_t EqPos=ArgIt->find('=');
+ if (EqPos!=string::npos)
+ {
+ string Var=ArgIt->substr(0,EqPos);
+ string Val=ArgIt->substr(EqPos+1);
+ m_CommandLineVars[Var]=Val;
+ }
+ else if ((*ArgIt)[0]=='-')
+ {
+ switch ((*ArgIt)[1])
+ {
+ case 'f':
+ if (ArgIt->size()>2)
+ {
+ if (!m_MakeDir)
+ {
+ m_Makefile=GetFileInfo(ArgIt->substr(2),pDir);
+ }
+ else
+ {
+ m_Makefile=GetFileInfo(ArgIt->substr(2),m_MakeDir);
+ }
+ }
+ else
+ {
+ ArgIt++;
+ if (!m_MakeDir)
+ {
+ m_Makefile=GetFileInfo(*ArgIt,pDir);
+ }
+ else
+ {
+ m_Makefile=GetFileInfo(*ArgIt,m_MakeDir);
+ }
+ }
+ break;
+ case 'C':
+#ifdef _DEBUG
+ if (ArgIt->size()>2 && (*ArgIt)[2]=='D')
+ {
+ g_CheckCircularDeps=true;
+ break;
+ }
+#endif
+ /* Fall through */
+ case 'c':
+ if (ArgIt->size()>2)
+ m_MakeDir=GetFileInfo(ArgIt->substr(2),pDir);
+ else
+ {
+ ArgIt++;
+ m_MakeDir=GetFileInfo(*ArgIt,pDir);
+ }
+ break;
+ case 'a':
+ g_RebuildAll=true;
+ break;
+ case 'q':
+ g_Quiet=true;
+ break;
+ case 's':
+ g_ForceAutoDepRescan=true;
+ break;
+ case 'S':
+ g_SkipMhMakeConfDirCheck=true;
+ break;
+ case 'v':
+ PrintVersionInfo();
+ break;
+ case 'P':
+ if (ArgIt->size()>2)
+ mhmakefileparser::SetNrParallelBuilds(atoi(ArgIt->substr(2).c_str()));
+ else
+ {
+ ArgIt++;
+ mhmakefileparser::SetNrParallelBuilds(atoi((*ArgIt).c_str()));
+ }
+ break;
+#ifdef _DEBUG
+ case 'p':
+ g_PrintVarsAndRules=true;
+ break;
+ case 'n':
+ g_DoNotExecute=true;
+ break;
+ case 'w':
+ g_PrintAdditionalInfo=true;
+ break;
+ case 'd':
+ g_pPrintDependencyCheck=true;
+ break;
+ case 'D':
+ g_PrintMultipleDefinedRules=true;
+ break;
+ case 'l':
+ g_PrintLexYacc=true;
+ break;
+ case 'e':
+ g_DumpOnError=true;
+ break;
+ case 'm':
+ g_BuildMd5Db=true;
+ break;
+ case 'b':
+ g_GenProjectTree=true;
+ break;
+#endif
+ default:
+ throw string("\nUnknown option: ")+*ArgIt+"\n\n"+ s_UsageString;
+ }
+ }
+ else
+ {
+ m_CommandLineTargets.push_back(*ArgIt);
+ }
+ ArgIt++;
+ }
+ if (!m_Makefile)
+ {
+ if (!Makefile.empty())
+ {
+ if (!m_MakeDir)
+ m_Makefile=GetFileInfo(Makefile,pDir);
+ else
+ m_Makefile=GetFileInfo(Makefile,m_MakeDir);
+ }
+ }
+ if (!m_Makefile)
+ {
+ if (!m_MakeDir)
+ m_Makefile=GetFileInfo(m_CommandLineTargets[0],pDir);
+ else
+ m_Makefile=GetFileInfo(m_CommandLineTargets[0],m_MakeDir);
+
+ m_CommandLineTargets.erase(m_CommandLineTargets.begin());
+ }
+ if (!m_MakeDir)
+ {
+ if (Makefile==g_EmptyString)
+ m_MakeDir=m_Makefile->GetDir(); /* This is one from load_makefile, so we take the directory of the makefile itself. */
+ else
+ m_MakeDir=curdir::GetCurDir(); /* This means that this is the main makefile given on the command line, so we take the current directory */
+ }
+
+ if (!g_SkipMhMakeConfDirCheck)
+ {
+ if (loadedmakefile::sm_Statics.m_MhMakeConf)
+ {
+ const string &RootDir=loadedmakefile::sm_Statics.m_MhMakeConf->GetFullFileName();
+ string MakeDir=m_MakeDir->GetFullFileName();
+ if (RootDir.length()>MakeDir.length() || strncmp(RootDir.c_str(),MakeDir.c_str(),RootDir.length()))
+ {
+ cerr<<"mhmake needs to run in a directory that is a subdirectory of the directory specified with %MHMAKECONF : "<<RootDir<<", make dir : "<<m_MakeDir->GetFullFileName()<<"\nComparison is case sensitive!\n";
+ exit(1);
+ }
+ }
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+void loadedmakefile::LoadMakefile()
+{
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "Loading makefile "<<m_Makefile->GetQuotedFullFileName()<<endl;
+ #endif
+
+ m_pMakefileParser=refptr<mhmakefileparser>(new mhmakefileparser(m_CommandLineVars));
+
+ // Add the MAKECMDGOALS environment variable
+ string MakeCmdGoals;
+ bool First=true;
+ vector<string>::iterator TarIt=m_CommandLineTargets.begin();
+ while (TarIt!=m_CommandLineTargets.end())
+ {
+ if (First)
+ First=false;
+ else
+ MakeCmdGoals+=g_SpaceString;
+ MakeCmdGoals+=*TarIt;
+ TarIt++;
+ }
+ m_pMakefileParser->SetVariable("MAKECMDGOALS",MakeCmdGoals);
+
+ string BaseAutoMak;
+
+ // First parse the makefile.before makefile which is in the directory $(MHMAKECONF) environment variable
+ fileinfo *pDepFile;
+ if (sm_Statics.m_MhMakeConf)
+ {
+ BaseAutoMak=m_pMakefileParser->ExpandVar(BASEAUTOMAK);
+ if (BaseAutoMak.empty())
+ {
+ BaseAutoMak="makefile";
+ m_pMakefileParser->SetVariable(BASEAUTOMAK,BaseAutoMak);
+ }
+ const fileinfo *pBeforeMakefile=GetFileInfo(BaseAutoMak+".before",sm_Statics.m_MhMakeConf);
+
+ int result=m_pMakefileParser->ParseFile(pBeforeMakefile,m_MakeDir);
+ if (result)
+ {
+ throw string("Error parsing ")+pBeforeMakefile->GetQuotedFullFileName();
+ }
+ m_pMakefileParser->UpdateDate(pBeforeMakefile->GetDate());
+
+ // Now parse the automaticly generated dependency file, which needs to be in the objdir directory
+ string ObjDirName=m_pMakefileParser->ExpandExpression("$(OBJDIR)");
+ if (!ObjDirName.size())
+ {
+ throw string("When making use of MHMAKECONF, you have to define OBJDIR in makefile.before");
+ }
+ pDepFile=GetFileInfo(ObjDirName+OSPATHSEPSTR "." + m_Makefile->GetName()+ ".dep",m_MakeDir);
+ m_pMakefileParser->SetVariable(AUTODEPFILE,pDepFile->GetQuotedFullFileName());
+ }
+ else
+ {
+ /* Create a file that is depending on the makefile name and the arguments */
+ md5_context ctx;
+
+ md5_starts( &ctx );
+
+ map<string,string>::const_iterator pIt=m_CommandLineVars.begin();
+ while (pIt!=m_CommandLineVars.end())
+ {
+ if (pIt->first!="MAKE")
+ {
+ md5_update(&ctx, (uint8*)pIt->first.c_str(), pIt->first.size());
+ md5_update(&ctx, (uint8*)pIt->second.c_str(), pIt->second.size());
+ }
+ pIt++;
+ }
+ md5_update(&ctx, (uint8*)m_Makefile->GetFullFileName().c_str(), m_Makefile->GetFullFileName().size());
+
+ char ID[10];
+ sprintf(ID,"_%lx",md5_finish32( &ctx));
+
+ pDepFile=GetFileInfo(string(".") + m_Makefile->GetName()+ ".dep"+ID,m_MakeDir);
+ m_pMakefileParser->SetVariable(AUTODEPFILE,pDepFile->GetQuotedFullFileName());
+ }
+
+ if (pDepFile->Exists())
+ m_pMakefileParser->LoadAutoDepsFile(pDepFile); /* Already load this autodep file before parsing of the makefile to avoid needless rebuilds. */
+
+ //m_pMakefileParser->yydebug=1;
+ int result=m_pMakefileParser->ParseFile(m_Makefile,m_MakeDir);
+ if (result)
+ {
+ throw string("Error parsing ")+m_Makefile->GetQuotedFullFileName();
+ }
+ #ifdef _DEBUG
+ /* Check if the makefile has changed the AUTODEPFILE variable, if so generate a warning that a
+ * rebuild could happen for the rules defined for making included makefiles */
+ if (m_pMakefileParser->ExpandVar(AUTODEPFILE)!=pDepFile->GetQuotedFullFileName())
+ {
+ cout << "\n\nWARNING:\n makefile '"<< m_Makefile->GetQuotedFullFileName() <<"' re-defines AUTODEPFILE\n from '"<< pDepFile->GetQuotedFullFileName() <<"'\n to '"<<
+ m_pMakefileParser->ExpandVar(AUTODEPFILE) << "'\n (may cause needless rebuilds when having rules for included makefiles!!!!!)\n\n\n";
+ }
+
+ if (g_PrintAdditionalInfo)
+ {
+ if (m_pMakefileParser->GetFirstTarget())
+ cout<<"First target of "<<m_Makefile->GetQuotedFullFileName()<<" is "<<m_pMakefileParser->GetFirstTarget()->GetQuotedFullFileName()<<endl;
+ else
+ cout<<"No First target for "<<m_Makefile->GetQuotedFullFileName()<<endl;
+ }
+ #endif
+ m_pMakefileParser->UpdateDate(m_Makefile->GetDate());
+
+ if (sm_Statics.m_MhMakeConf)
+ {
+ fileinfo *pAfterMakefile=GetFileInfo(BaseAutoMak+".after",sm_Statics.m_MhMakeConf);
+ int result=m_pMakefileParser->ParseFile(pAfterMakefile);
+ if (result) {
+ throw string("Error parsing ")+pAfterMakefile->GetQuotedFullFileName();
+ }
+ m_pMakefileParser->UpdateDate(pAfterMakefile->GetDate());
+ }
+ bool ForceAutoDepRescan=g_ForceAutoDepRescan;
+ if (pDepFile->Exists())
+ m_pMakefileParser->LoadAutoDepsFile(pDepFile);
+ else
+ ForceAutoDepRescan=true;
+ if (ForceAutoDepRescan)
+ m_pMakefileParser->EnableAutoDepRescan();
+
+ vector<string> &MakefilesToLoad=m_pMakefileParser->GetMakefilesToLoad();
+ vector<string>::iterator It=MakefilesToLoad.begin();
+ while (It!=MakefilesToLoad.end())
+ {
+ // First split the command into arguments
+ const char *pTmp=It->c_str();
+ vector<string> Args;
+ while (*pTmp)
+ {
+ string Item;
+ pTmp=NextItem(pTmp,Item);
+ Args.push_back(Item);
+ }
+
+ refptr<loadedmakefile> pLoadedMakefile(new loadedmakefile(m_MakeDir,Args));
+ refptr<loadedmakefile> Found=g_LoadedMakefiles.find(*pLoadedMakefile);
+ if (Found)
+ {
+ #ifdef _DEBUG
+ if (g_PrintAdditionalInfo)
+ cout << "Makefile already loaded: "<<Found->m_Makefile->GetQuotedFullFileName()<<endl;
+ #endif
+ }
+ else
+ {
+ g_LoadedMakefiles.push_back(pLoadedMakefile);
+
+ /* If there is a rule to build the makefile, first check if it needs to be rebuild */
+ m_pMakefileParser->BuildTarget(pLoadedMakefile->m_Makefile);
+ pLoadedMakefile->LoadMakefile();
+ }
+ It++;
+ }
+}
+
+/*****************************************************************************/
+bool MakeDirs(fileinfo *pDir)
+{
+ fileinfo *pParentDir=pDir->GetDir();
+ if (!pParentDir->GetDate().DoesExist())
+ { /* First make parent dirs */
+ if (!MakeDirs(pParentDir))
+ return false;
+ }
+ if (!pDir->GetDate().DoesExist())
+ { /* Create directory */
+ struct stat statbuf;
+ if ( (-1==stat(pParentDir->GetFullFileName().c_str(),&statbuf)) ||
+ (-1==mkdir(pDir->GetFullFileName().c_str(),statbuf.st_mode))
+ )
+ {
+ cerr << "mkdir function failed for directory " << QuoteFileName(pDir->GetFullFileName()) << endl;
+ return false;
+ }
+ pDir->InvalidateDate(); // Directory created successfully, so invalidate the date
+ }
+ return true;
+}
+
+#ifdef _DEBUG
+///////////////////////////////////////////////////////////////////////////////
+void DumpVarsAndRules()
+{
+ int i;
+ LOADEDMAKEFILES::iterator LoadMakIt=g_LoadedMakefiles.begin();
+ while (LoadMakIt!=g_LoadedMakefiles.end())
+ {
+ for (i=0; i<80; i++) cout << "_";
+ cout << endl;
+ cout << "Variables of makefile " << (*LoadMakIt)->m_Makefile->GetQuotedFullFileName() << endl;
+ for (i=0; i<80; i++) cout << "_";
+ cout << endl;
+ (*LoadMakIt)->m_pMakefileParser->PrintVariables(true);
+ cout << endl;
+ LoadMakIt++;
+ }
+ for (i=0; i<80; i++) cout << "_";
+ cout << endl;
+ cout << "All Rules\n";
+ for (i=0; i<80; i++) cout << "_";
+ cout << endl;
+ PrintFileInfos();
+ for (i=0; i<80; i++) cout << "_";
+ cout << endl;
+ cout << "All Implicit Rules\n";
+ for (i=0; i<80; i++) cout << "_";
+ cout << endl;
+ IMPLICITRULE::PrintImplicitRules();
+}
+#endif
+
diff --git a/tools/mhmake/src/util.h b/tools/mhmake/src/util.h
new file mode 100644
index 000000000..adb154497
--- /dev/null
+++ b/tools/mhmake/src/util.h
@@ -0,0 +1,279 @@
+/* This file is part of mhmake.
+ *
+ * Copyright (C) 2001-2010 marha@sourceforge.net
+ *
+ * Mhmake is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Mhmake is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* $Rev$ */
+
+#ifndef __UTIL_H__
+#define __UTIL_H__
+
+#include "fileinfo.h"
+
+// List of pre-defined variables
+#define WC_REVISION "WC_REVISION"
+#define WC_URL "WC_URL"
+#define AUTODEPFILE "AUTODEPFILE"
+#define OBJEXTVAR "OBJEXT"
+#define EXEEXTVAR "EXEEXT"
+#define SKIPHEADERS "SKIPHEADERS"
+#define MAKE "MAKE"
+#define MHMAKECONF "MHMAKECONF"
+#define BASEAUTOMAK "BASEAUTOMAK"
+#define CURDIR "CURDIR"
+#define USED_ENVVARS "USED_ENVVARS"
+#define PATH "PATH"
+#ifdef WIN32
+#define COMSPEC "COMSPEC"
+#define PYTHONEXE "python.exe"
+#define EXEEXT ".exe"
+#define OBJEXT ".obj"
+#define PLATFORM "win32"
+#else
+#define COMSPEC "SHELL"
+#define PYTHONEXE "python"
+#define EXEEXT ""
+#define OBJEXT ".o"
+#define PLATFORM "linux"
+#endif
+
+#define MHMAKEVER "3.0.9"
+
+class makecommand
+{
+ string m_BuildCommand;
+public:
+ makecommand();
+ operator string()
+ {
+ return m_BuildCommand;
+ }
+};
+
+extern makecommand g_MakeCommand;
+
+///////////////////////////////////////////////////////////////////////////////
+inline const char *NextItem(const char *pTmp,string &Output, const char *pToks=" \t")
+{
+ const char *pStart;
+ const char *pStop;
+ while (strchr(pToks,*pTmp)&&*pTmp) pTmp++;
+ pStart=pTmp;
+ while (1)
+ {
+ if (*pTmp=='"')
+ {
+ pTmp++;
+ while (*pTmp && *pTmp!='"') pTmp++;
+ if (*pTmp) pTmp++;
+ pStop=pTmp;
+ if (!*pTmp || strchr(pToks,*pTmp))
+ break;
+ }
+ else if (*pTmp=='\'')
+ {
+ pTmp++;
+ while (*pTmp && *pTmp!='\'') pTmp++;
+ if (*pTmp) pTmp++;
+ pStop=pTmp;
+ if (!*pTmp || strchr(pToks,*pTmp))
+ break;
+ }
+ else if (!*pTmp)
+ {
+ pStop=pTmp;
+ break;
+ }
+ else
+ {
+ pTmp++;
+ #if OSPATHSEP=='/'
+ while (*pTmp)
+ {
+ if (!strchr(pToks,*pTmp) || (*(pTmp-1)=='\\'))
+ pTmp++;
+ else
+ break;
+ }
+ #else
+ while (!strchr(pToks,*pTmp)) pTmp++;
+ #endif
+ pStop=pTmp;
+ break;
+ }
+ }
+ Output=string(pStart,pStop);
+ // skip trailing space
+ while (strchr(pToks,*pTmp)&&*pTmp) pTmp++;
+ return pTmp;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+inline const char *NextCharItem(const char *pTmp,string &Output,char Char)
+{
+ const char *pStart=pTmp;
+ while (*pTmp && *pTmp!=Char) pTmp++;
+ const char *pStop=pTmp;
+ if (*pTmp) pTmp++;
+
+ while (pStart<pStop && (*pStart==' ' || *pStart == '\t')) pStart++;
+ pStop--;
+ while (pStart<=pStop && (*pStop==' ' || *pStop == '\t')) pStop--;
+ pStop++;
+
+ Output=string(pStart,pStop);
+ return pTmp;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+inline const char *SkipMakeExpr(const char *pMacro)
+{
+#ifdef _DEBUG
+ const char *pMacroIn=pMacro;
+#endif
+ char Char=*pMacro++;
+ char EndChar;
+ if (Char=='(')
+ EndChar=')';
+ else if (Char=='{')
+ EndChar='}';
+ else
+ return pMacro;
+ Char=*pMacro++;
+ while (Char!=EndChar)
+ {
+ if (Char=='$')
+ {
+ pMacro=SkipMakeExpr(pMacro);
+ } else if (Char=='(')
+ {
+ pMacro=SkipMakeExpr(pMacro-1);
+ }
+#ifdef _DEBUG
+ if (!*pMacro)
+ throw(string(1,EndChar)+" not found in "+pMacroIn);
+#endif
+ Char=*pMacro++;
+ }
+ return pMacro;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+inline size_t SkipMakeExpr(const string &Expr,size_t i)
+{
+ const char *pTmp=Expr.c_str();
+ return SkipMakeExpr(pTmp+i)-pTmp;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+string Substitute(const string &ToSubst,const string &SrcStr,const string &ToStr);
+
+struct matchres
+{
+ string m_First;
+ string m_Stem;
+ string m_Last;
+};
+
+bool PercentMatch(const string &String,const string &Expr,matchres *pRes=NULL,const char Char='%');
+bool PercentMatchNoCase(const string &String,const string &Expr,matchres *pRes=NULL,const char Char='%');
+bool PercentMatchList(const string &String,const string &ExprList,matchres *pRes=NULL);
+string ReplaceWithStem(const string &String,const string &Stem);
+
+struct loadedmakefile : public refbase
+{
+ struct loadedmakefile_statics
+ {
+ map<string,string> m_GlobalCommandLineVars;
+ fileinfo *m_MhMakeConf;
+
+ loadedmakefile_statics();
+ };
+ static loadedmakefile_statics sm_Statics;
+
+ fileinfo *m_Makefile;
+ const fileinfo *m_MakeDir;
+ map<string,string> m_CommandLineVars;
+
+ vector<string> m_CommandLineTargets;
+ refptr<mhmakefileparser> m_pMakefileParser;
+
+ loadedmakefile(const fileinfo *pDir, vector<string> &Args,const string &Makefile=g_EmptyString);
+
+ void LoadMakefile();
+ void AddCommandLineVarsToEnvironment()
+ {
+ map<string,string>::const_iterator It=m_CommandLineVars.begin();
+ map<string,string>::const_iterator ItEnd=m_CommandLineVars.end();
+ while (It!=ItEnd)
+ {
+ sm_Statics.m_GlobalCommandLineVars.insert(*It++);
+ }
+ }
+
+ int operator==(const loadedmakefile &Other)
+ {
+ if (m_Makefile!=Other.m_Makefile)
+ return 0;
+ if (m_MakeDir!=Other.m_MakeDir)
+ return 0;
+ if (m_CommandLineTargets.size()!=Other.m_CommandLineTargets.size())
+ return 0;
+ if (m_CommandLineVars.size()!=Other.m_CommandLineVars.size())
+ return 0;
+ map<string,string>::iterator VarIt=m_CommandLineVars.begin();
+ while (VarIt!=m_CommandLineVars.end())
+ {
+ map<string,string>::const_iterator pFound=Other.m_CommandLineVars.find(VarIt->first);
+ if (pFound==Other.m_CommandLineVars.end())
+ return 0;
+ if (pFound->second!=VarIt->second)
+ return 0;
+ VarIt++;
+ }
+ vector<string>::iterator TarIt=m_CommandLineTargets.begin();
+ while (TarIt!=m_CommandLineTargets.end())
+ {
+ vector<string>::const_iterator OtherIt=Other.m_CommandLineTargets.begin();
+ while (OtherIt!=Other.m_CommandLineTargets.begin())
+ {
+ if (*TarIt==*OtherIt)
+ break;
+ OtherIt++;
+ }
+ if (OtherIt==Other.m_CommandLineTargets.end())
+ return 0;
+ TarIt++;
+ }
+ return 1;
+ }
+};
+
+class LOADEDMAKEFILES : public vector<refptr<loadedmakefile> >
+{
+public:
+ refptr<loadedmakefile> find(const loadedmakefile &pToSearch);
+ typedef vector<refptr<loadedmakefile> >::iterator iterator;
+};
+
+extern LOADEDMAKEFILES g_LoadedMakefiles;
+
+bool MakeDirs(fileinfo *pDir); // Creates a directory tree
+void DumpVarsAndRules();
+
+#endif
+