Está en la página 1de 20

Estructura lxica de Visual Basic

Los lenguajes de programacin, como las lenguas humanas, tienen una estructura lxica. Un cdigo fuente de un programa de Visual Basic consta de fichas. Tokens son elementos de cdigo atmicas. En Visual Basic, tenemos comentarios, variables, literales, operadores delimitadores y palabras clave. Programas de Visual Basic se componen de caracteres del juego de caracteres Unicode.

Comentarios
Comments

son utilizados por los seres humanos para aclarar el cdigo fuente. Todos los comentarios en

Visual Basic siguen ya sea el ' carcter o el Rem palabra clave.


Option Strict On ' This is comments.vb ' Author: Jan Bodnar ' ZetCode 2010 Module Example Rem program starts here Sub Main() Console.WriteLine("This is comments.vb") End Sub End Module

Los comentarios son ignorados por el compilador de Visual Basic.

El espacio en blanco
El espacio en blanco en Visual Basic se utiliza para separar tokens en el archivo de origen. Se utiliza para mejorar la legibilidad del cdigo fuente. Dim i As Integer Los espacios en blanco son necesarios en algunos lugares. Por ejemplo entre el Dim palabra clave y el nombre de la variable. En otros lugares, est prohibido. No puede estar presente en los identificadores de variables o palabras clave del lenguaje.
a=1 b = 2 c = 3

La cantidad de espacio puesto entre fichas es irrelevante para el compilador de Visual Basic.

Carcter de continuacin de lnea


Debemos utilizar un carcter de continuacin de lnea, si una declaracin se extiende por ms de una lnea. Esto difiere de los lenguajes basados en C y C.
Console.WriteLine ("La longitud de la primera cadena es" _ + Str1.Length.ToString () + "caracteres")

Principalmente por razones de legibilidad, no quiero tener demasiados caracteres en una lnea. Rompemos la lnea y continuar en la siguiente lnea. En Visual Basic, hay que utilizar el carcter de continuacin de lnea, de lo contrario la compilacin fallara.

Variables
A la variable es un identificador, que tiene un valor. En la programacin de nuestras palabras, que se le asigna un valor a una variable. Hablando tcnicamente, una variable es una referencia a una memoria de ordenador, en donde se almacena el valor. Los nombres de variables pueden tener caracteres alfanumricos y guiones bajos. Un identificador puede comenzar con un carcter o un guin bajo. No puede comenzar con un nmero. Los nombres de variables no distinguen entre maysculas y minsculas. Esto significa que, Name, name o NAME se refieren a la misma variable. Los nombres de variables tambin no pueden igualar palabras clave del lenguaje.
Dim name23 As String Dim _col As Integer Dim birth_date As Date

Estos son identificadores vlidos de Visual Basic.


Option Strict On Module Example Sub Main() Dim name As String = "Robert" Dim Name As String = "Julia" Console.WriteLine(name) Console.WriteLine(Name) End Sub End Module

Este cdigo no se compilar. Los identificadores no distinguen entre maysculas y minsculas.

Literales
Un literal es una representacin textual de un valor particular de un tipo. Tipos literales son: Boolean, Integer, floating point, string, character y date. Tcnicamente, un literal se le asignar un valor en tiempo de compilacin, mientras que una variable se le asigna en tiempo de ejecucin.
Dim age As Byte = 29 Dim nationality As String = "Hungarian"

Aqu asignamos dos literales a variables. Nmero 29 y la cadena " Hungarian " son literales.
Option Strict On Module Example Sub Main() Dim Dim Dim Dim Dim Dim sng As Boolean = True name As String = "James" job As String = Nothing age As Byte = 23 weight As Single = 68.5 born As DateTime = DateValue("November 12, 1987")

Console.WriteLine("His name is {0}", name)

If sng Then Console.WriteLine("He is single") Else Console.WriteLine("He is in a relationship") End If Console.WriteLine("His job is {0}", job) Console.WriteLine("He weighs {0} kilograms", weight) Console.WriteLine("He was born in {0}", _ Format(born, "yyyy")) End Sub End Module

En el ejemplo anterior, tenemos otros literales. El literal booleano puede tener valor True o
False. James es

una cadena literal. El Nothing representa el valor por defecto de cualquier tipo de

datos. 23 es un entero literal. 68.5 es un literal de coma flotante. Finalmente, el November 12, 1987 es un literal de fecha.
$ ./literals.exe His name is James He is single His job is He weighs 68.5 kilograms He was born in 1987

Esta es la salida del programa.

Operadores
Un operador es un smbolo que se utiliza para llevar a cabo una accin sobre algn valor.
+ = < >> += > <> * -= &= << / *= >>= \ /= <<= ^ \= >= & ^= <=

Estos son los operadores de Visual Basic. Vamos a hablar de los operadores ms adelante en el tutorial.

Separadores
Un separador es una secuencia de uno o ms caracteres utilizados para especificar el lmite entre las regiones separadas, independientes en texto plano o de otro flujo de datos.
( ) { } ! # , . : := ?

Estos son los separadores de Visual Basic.


Dim language As String = "Visual Basic"

Los personajes dobles se utilizan para marcar el comienzo y el final de una cadena.
Console.WriteLine("Today is {0}", GetToday)

Los parntesis (corchetes) se utilizan para marcar la firma del mtodo. La firma consta de los parmetros del mtodo. Las llaves se usan para indicar el valor evaluado.
Dim array() As Integer = { _ 2, 4, 5, 6, 7, 3, 2 }

Las llaves tambin se utilizan para crear matrices.

Palabras clave
Una palabra clave es una palabra reservada en el lenguaje Visual Basic. Las palabras clave se utilizan para realizar una tarea especfica en el programa informtico. Por ejemplo, imprimir un valor, hacer tareas repetitivas o realizar operaciones lgicas. Un programador no puede utilizar una palabra clave como una variable normal. Visual Basic es rico en palabras clave. Muchos de ellos se explican en este tutorial. Las palabras clave incluyen If, Else, Dim, For, Date, Double, Or, Exit y muchos otros.
Option Strict On Module Example Sub Main() Dim i As Integer For i = 0 To 35 Step 5 Console.WriteLine(i) Next End Sub End Module

En el ejemplo anterior, usamos varias palabras clave. Option, On, Module, Sub, Dim, As, Integer, For, To, Step, Next, End son palabras clave de Visual Basic.

12. Resumen gramatical de Visual Basic .NET


Visual Studio .NET 2003 Esta seccin resume la gramtica del lenguaje de Visual Basic. Para ms informacin sobre cmo leer la gramtica, vea Notacin gramatical.

Gramtica lxica
Start ::= [ LogicalLine+ ] LogicalLine ::= [ LogicalLineElement+ ] [ Comment ] LineTerminator LogicalLineElement ::= WhiteSpace | Token Token ::= Identifier | Keyword | Literal | Separator | Operador

Caracteres y lneas
Character ::= < any Unicode character except a LineTerminator >

Terminadores de lnea
LineTerminator ::= < Unicode carriage return character (0x000D) > | < Unicode line feed character (0x000A) > | < Unicode carriage return character > < Unicode line feed character > | < Unicode line separator character (0x2028) > | < Unicode paragraph separator character (0x2029) >

Continuacin de lnea
LineContinuation ::= WhiteSpace _ [ WhiteSpace+ ] LineTerminator

Espacio en blanco
WhiteSpace ::= < Unicode blank characters (class Zs) > | LineContinuation

Comentarios
Comment ::= CommentMarker [ Character+ ] CommentMarker ::= ' | REM

Identificadores
Identifier ::= NonEscapedIdentifier [ TypeCharacter ] | EscapedIdentifier NonEscapedIdentifier ::= < IdentifierName but not Keyword > EscapedIdentifier ::= [ IdentifierName ] IdentifierName ::= IdentifierStart [ IdentifierCharacter+ ] IdentifierStart ::= AlphaCharacter | UnderscoreCharacter IdentifierCharacter IdentifierCharacter ::= UnderscoreCharacter | AlphaCharacter | NumericCharacter | CombiningCharacter | FormattingCharacter AlphaCharacter ::= < Unicode alphabetic character (classes Lu, Ll, Lt, Lm, Lo, Nl) > NumericCharacter ::= < Unicode decimal digit character (class Nd) > CombiningCharacter ::= < Unicode combining character (classes Mn, Mc) > FormattingCharacter ::= < Unicode formatting character (class Cf) > UnderscoreCharacter ::= < Unicode connection character (class Pc) > IdentifierOrKeyword ::= Identifier | Palabra clave

Caracteres de tipo
TypeCharacter ::= IntegerTypeCharacter | LongTypeCharacter | DecimalTypeCharacter |

SingleTypeCharacter | DoubleTypeCharacter | StringTypeCharacter IntegerTypeCharacter ::= % LongTypeCharacter ::= & DecimalTypeCharacter ::= @ SingleTypeCharacter ::= ! DoubleTypeCharacter ::= # StringTypeCharacter ::= $

Palabras clave
Keyword ::= < member of keyword table at Keywords >

Literales
Literal ::= BooleanLiteral | NumericLiteral | StringLiteral | CharacterLiteral | DateLiteral | Nothing NumericLiteral ::= IntegerLiteral | FloatingPointLiteral

Literales booleanos
BooleanLiteral ::= True | False

Literales enteros
IntegerLiteral ::= IntegralLiteralValue [ IntegralTypeCharacter ] IntegralLiteralValue ::= IntLiteral | HexLiteral | OctalLiteral IntegralTypeCharacter ::= ShortCharacter | IntegerCharacter | LongCharacter | IntegerTypeCharacter | LongTypeCharacter ShortCharacter ::= S IntegerCharacter ::= I LongCharacter ::= L IntLiteral ::= Digit+ HexLiteral ::= & H HexDigit+ OctalLiteral ::= & O OctalDigit+ Digit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 HexDigit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F OctalDigit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7

Literales de punto flotante


FloatingPointLiteral ::= FloatingPointLiteralValue [ FloatingPointTypeCharacter ] | IntLiteral FloatingPointTypeCharacter FloatingPointTypeCharacter ::= SingleCharacter | DoubleCharacter | DecimalCharacter | SingleTypeCharacter | DoubleTypeCharacter | DecimalTypeCharacter SingleCharacter ::= F DoubleCharacter ::= R DecimalCharacter ::= D FloatingPointLiteralValue ::= IntLiteral . IntLiteral [ Exponent ] | IntLiteral [ Exponent ] | IntLiteral Exponent Exponent ::= E [ Sign ] IntLiteral Sign ::= + | -

Literales de cadena

StringLiteral ::= " [ StringCharacter+ ] " StringCharacter ::= < Character except for " > | ""

Literales de carcter
CharacterLiteral ::= " StringCharacter " C

Literales de fecha
DateLiteral ::= # [ Whitespace+ ] [ DateValue ] [ Whitespace+ ] [ TimeValue ] [ Whitespace+ ] # DateValue ::= MonthValue DateSeparator DayValue DateSeparator YearValue DateSeparator ::= / | TimeValue ::= HourValue [ : MinuteValue ] [ : SecondValue ] [ Whitespace+ ] [ AMPM ] MonthValue ::= IntLiteral DayValue ::= IntLiteral YearValue ::= IntLiteral HourValue ::= IntLiteral MinuteValue ::= IntLiteral SecondValue ::= IntLiteral AMPM ::= AM | PM

Nothing
Nothing ::= Nothing

Separadores
Separator ::= ( | ) | ! | # | , | . | :

Caracteres de operador
Operator ::= & | * | + | - | / | \ | ^ | < | = | >

Preprocessing Directives
Directivas de compilacin condicional
Source ::= [ ConditionalElement+ ] ConditionalElement ::= ConditionalIfGroup | ConditionalConstantDeclaration | LogicalLine

Constantes condicionales
ConditionalConstantDeclaration ::= # Const IdentifierOrKeyword = ConstantExpression LineTerminator

Instrucciones de compilacin condicional


ConditionalElseIfGroup ::= # ElseIf ConstantExpression [ Then ] LineTerminator [ ConditionalElement+ ]

Directivas de origen externo


Source ::= [ ExternalSourceElement+ ] ExternalSourceElement ::= ExternalSourceGroup | LogicalLine ExternalSourceGroup ::= # ExternalSource ( StringLiteral , IntLiteral ) LineTerminator [ LogicalLine+ ] # End ExternalSource LineTerminator

Directivas de regin
Start ::= [ RegionElement+ ] RegionElement ::= RegionGroup | LogicalLine RegionGroup ::= # Region [ NoDebug ] StringLiteral LineTerminator [ LogicalLine+ ] # End Region LineTerminator ConditionalElseGroup ::= # Else LineTerminator [ ConditionalElement+ ]

Conceptos generales
Accesibilidad
AccessModifier ::= Public | Protected | Friend | Private

Nombres de tipos y espacios de nombres


QualifiedIdentifier ::=

Identifier | QualifiedIdentifier . IdentifierOrKeyword

Bloques de atributos
Attributes ::= < AttributeList > AttributeList ::= Attribute | AttributeList , Attribute Attribute ::= [ AttributeModifier : ] TypeName [ ( [ AttributeArguments ] ) ] AttributeModifier ::= Assembly | Mdulo

Argumentos de atributos
AttributeArguments ::= AttributePositionalArgumentList | AttributePositionalArgumentList , VariablePropertyInitializerList | VariablePropertyInitializerList AttributePositionalArgumentList ::= ConstantExpression | AttributePositionalArgumentList , ConstantExpression VariablePropertyInitializerList ::= VariablePropertyInitializer VariablePropertyInitializerList , VariablePropertyInitializer VariablePropertyInitializer ::= Identifier : = ConstantExpression

Archivos de cdigo fuente y espacios de nombres


Source ::= [ OptionDirective+ ] [ ImportsDirective+ ] [ Attributes ] [ NamespaceBody ]

Opciones de compilacin
OptionDirective ::= OptionExplicitDirective | OptionStrictDirective | OptionCompareDirective

Instruccin Option Explicit


OptionExplicitDirective ::= Option Explicit [ OnOff ] LineTerminator OnOff ::= On | Desactivado

Instruccin Option Strict


OptionStrictDirective ::= Option Strict [ OnOff ] LineTerminator

Instruccin Option Compare


OptionCompareDirective ::= Option Compare CompareOption LineTerminator CompareOption ::= Binary | Text

Instruccin Imports
ImportsDirective ::= Imports ImportsClauses LineTerminator ImportsClauses ::= ImportsClause | ImportsClauses , ImportsClause ImportsClause ::= ImportsAliasClause | RegularImportsClause

Alias de importacin
ImportsAliasClause ::= Identifier = QualifiedIdentifier

Importaciones regulares
ImportsNamespaceClause ::= QualifiedIdentifier

Declaraciones de espacios de nombres


NamespaceDeclaration ::= Namespace QualifiedIdentifier LineTerminator [ NamespaceMemberDeclaration+ ] End Namespace LineTerminator

Miembros de espacios de nombres


NamespaceMemberDeclaration ::=

NamespaceDeclaration | TypeDeclaration TypeDeclaration ::= ModuleDeclaration | NonModuleDeclaration NonModuleDeclaration ::= EnumDeclaration | StructureDeclaration | InterfaceDeclaration | ClassDeclaration | DelegateDeclaration

Tipos
TypeName ::= QualifiedIdentifier | Object | PrimitiveTypeName | ClassTypeName | ArrayTypeName

Tipos primitivos
PrimitiveTypeName ::= NumericTypeName | Boolean | Date | Tipo Char NumericTypeName ::= IntegralTypeName | FloatingPointTypeName | Tipo Decimal IntegralTypeName ::= Byte | Short | Integer | Tipo Long FloatingPointTypeName ::= Single | Double

Enumeraciones
EnumDeclaration ::= [ Attributes ] [ EnumModifier+ ] Enum Identifier [ As IntegralTypeName ] LineTerminator EnumMemberDeclaration+ End Enum LineTerminator EnumModifier ::= AccessModifier | Shadows

Miembros de enumeraciones
EnumMemberDeclaration ::= [ Attributes ] Identifier [ = ConstantExpression ] LineTerminator

Estructuras
StructDeclaration ::= [ Attributes ] [ StructModifier+ ] Structure Identifier LineTerminator [ TypeImplementsClause+ ] [ StructMemberDeclaration+ ] End Structure LineTerminator StructureModifier ::= AccessModifier | Shadows

Implementaciones de interfaces de estructuras


TypeImplementsClause ::= Implements Implements LineTerminator Implements ::= TypeName | Implements , TypeName

Miembros de estructura
StructMemberDeclaration ::= NonModuleDeclaration VariableMemberDeclaration | ConstantMemberDeclaration | EventMemberDeclaration | MethodMemberDeclaration | PropertyMemberDeclaration | SharedConstructorDeclaration

Clases
ClassTypeName ::= String ClassDeclaration ::= [ Attributes ] [ ClassModifier+ ] Class Identifier LineTerminator [ ClassBase ]

[ TypeImplementsClause+ ] [ ClassMemberDeclaration+ ] End Class LineTerminator

Modificadores de clase
ClassModifier ::= AccessModifier | Shadows | MustInherit | NotInheritable

Especificacin base de clase


ClassBase ::= Inherits TypeName LineTerminator

Miembros de clase
ClassMemberDeclaration ::= NonModuleDeclaration | EventMemberDeclaration | VariableMemberDeclaration | ConstantMemberDeclaration | MethodMemberDeclaration | PropertyMemberDeclaration | ConstructorMemberDeclaration

Mdulos estndar
ModuleDeclaration ::= [ Attributes ] [ AccessModifier+ ] Module Identifier LineTerminator [ ModuleMemberDeclaration+ ] End Module LineTerminator

Miembros de mdulos estndar


ModuleMemberDeclaration ::= NonModuleDeclaration | VariableMemberDeclaration | ConstantMemberDeclaration | EventMemberDeclaration | MethodMemberDeclaration | PropertyMemberDeclaration | SharedConstructorDeclaration

Interfaces
InterfaceDeclaration ::= [ Attributes ] [ InterfaceModifier+ ] Interface Identifier LineTerminator [ InterfaceBases+ ] [ InterfaceMemberDeclaration+ ] End Interface LineTerminator InterfaceModifier ::= AccessModifier | Shadows

Herencia de interfaz
InterfaceBase ::= Inherits InterfaceBases LineTerminator InterfaceBases ::= TypeName InterfaceBases , TypeName

Miembros de interfaces
InterfaceMemberDeclaration ::= NonModuleDeclaration | EventMemberDeclaration | MethodMemberDeclaration | PropertyMemberDeclaration

Matrices
ArrayTypeName ::= TypeName ArrayTypeModifier ArrayTypeModifier ::= ( [ RankList ] ) RankList ::= ,| RankList ,

ArrayNameModifier ::= ArrayTypeModifier | ArrayInitializationModifier

Delegados
DelegateTypeDeclaration ::= [ DelegateModifier+ ] Delegate MethodDeclaration DelegateModifier ::= AccessModifier | Shadows

Miembros de tipo
Mtodos
MethodMemberDeclaration ::= MethodDeclaration | ExternalMethodDeclaration

Declaraciones de mtodos regulares


MethodDeclaration ::= SubDeclaration | FunctionDeclaration SubDeclaration ::= [ Attributes ] [ ProcedureModifier+ ] Sub Identifier [ ( [ FormalParameterList ] ) ] [ HandlesOrImplements ] LineTerminator [ Block ] [ End Sub LineTerminator ] FunctionDeclaration ::= [ Attributes ] [ ProcedureModifier+ ] Function Identifier [ ( [ FormalParameterList ] ) ] [ As [ Attributes ] TypeName ] [ HandlesOrImplements ] LineTerminator [ Block ] [ End Function LineTerminator ] ProcedureModifier ::= AccessModifier | Shadows | Shared | Overridable | NotOverridable | MustOverride | Overrides | Overloads HandlesOrImplements ::= HandlesClause | MethodImplementsClause

Declaraciones de mtodos regulares


ExternalMethodDeclaration ::= ExternalSubDeclaration | ExternalFunctionDeclaration ExternalSubDeclaration ::= [ Attributes ] [ ExternalMethodModifier+ ] Declare [ CharsetModifier ] Sub Identifier LibraryClause [ AliasClause ] [ ( [ FormalParameterList ] ) ] LineTerminator ExternalFunctionDeclaration ::= [ Attributes ] [ ExternalMethodModifier+ ] Declare [ CharsetModifier ] Function Identifier LibraryClause [ AliasClause ] [ ( [ FormalParameterList ] ) ] [ As [ Attributes ] TypeName ] LineTerminator ExternalMethodModifier ::= AccessModifier | Shadows | Overloads CharsetModifier ::= Ansi | Unicode | Auto LibraryClause ::= Lib StringLiteral AliasClause ::= Alias StringLiteral

Parmetros de mtodos
FormalParameterList ::= FormalParameter | FormalParameterList , FormalParameter FormalParameter ::= [ Attributes ] ParameterModifier+ Identifier [ As TypeName ] [ = ConstantExpression ] ParameterModifier ::= ByRef | ByVal | Optional | ParamArray

Implementaciones de mtodos de interfaz


ImplementsClause ::= [ Implements ImplementsList ]

ImplementsList ::= InterfaceMemberSpecifier | ImplementsList , InterfaceMemberSpecifier InterfaceMemberSpecifier ::= TypeName . Identificador

Control de eventos
HandlesClause ::= [ Handles EventHandlesList ] EventHandlesList ::= EventMemberSpecifier | EventHandlesList , EventMemberSpecifier EventMemberSpecifier ::= Identifier . [ Identifier . ] Identifier MyBase . [ Identifier . ] Identifier

Constructores
ConstructorMemberDeclaration ::= InstanceConstructorDeclaration | SharedConstructorDeclaration

Constructores de instancia
InstanceConstructorDeclaration ::= [ Attributes ] [ InstanceConstructorModifier+ ] Sub New [ ( [ FormalParameterList ] ) ] LineTerminator [ Block ] End Sub LineTerminator InstanceConstructorModifier ::= AccessModifier | Overloads

Miembros compartidos
SharedConstructorDeclaration ::= [ Attributes ] Shared Sub New [ ( ) ] LineTerminator [ Block ] End Sub LineTerminator

Eventos
EventMemberDeclaration ::= [ Attributes ] [ EventModifiers+ ] Event Identifier ParametersOrType [ ImplementsClause ] LineTerminator ParametersOrType ::= [ ( [ FormalParameterList ] ) ] | As TypeName

Constantes
ConstantMemberDeclaration ::= [ Attributes ] [ ConstantModifier+ ] Const Identifier [ As TypeName ] = ConstantExpression LineTerminator ConstantModifier ::= AccessModifiers | Shadows

Variables
VariableMemberDeclaration ::= [ Attributes ] [ VariableModifier+ ] [ Dim ] VariableDeclarators LineTerminator VariableModifier ::= AccessModifiers | Shadows | Shared | ReadOnly | WithEvents VariableDeclarators ::= VariableDeclarator | VariableDeclarators , VariableDeclarator VariableDeclarator ::= VariableIdentifiers [ As TypeName ] | VariableIdentifier [ As [ New ] TypeName [ ( ArgumentList ) ] ] [ = VariableInitializer ] VariableIdentifiers ::= VariableIdentifier | VariableIdentifiers , VariableIdentifier VariableIdentifier ::= Identifier [ ArrayNameModifier ]

Inicializadores de variables

VariableInitializer ::= RegularInitializer | ArrayElementInitializer

Inicializadores regulares
RegularInitializer ::= Expression

Inicializadores de elementos de matriz


ArrayElementInitializer ::= { [ VariableInitializerList ] } VariableInitializerList ::= VariableInitializer | VariableInitializerList , VariableInitializer VariableInitializer ::= Expression | ArrayElementInitializer

Inicializadores de tamao de matriz


ArrayInitializationModifier ::= ( InitializationRankList ) InitializationRankList ::= Expression | InitializationRankList , Expression

Propiedades
PropertyMemberDeclaration ::= [ Attributes ] PropertyModifier+ Property Identifier [ ( [ FormalParameterList ] ) ] [ As TypeName ] [ MethodImplementsClause ] LineTerminator PropertyAccessorDeclaration+ [ End Property LineTerminator ] PropertyModifier ::= ProcedureModifier | Default | ReadOnly | WriteOnly PropertyAccessorDeclaration ::= PropertyGetDeclaration | PropertySetDeclaration

Declaraciones de captadores
PropertyGetDeclaration ::= [ Attributes ] Get LineTerminator [ Block ] End Get

Declaraciones de establecedores
PropertySetDeclaration ::= [ Attributes ] Set LineTerminator [ Block ] End Set

Instrucciones
Bloques
Block ::= [ LabeledLine+ ] LabeledLine ::= [ LabelName : ] [ Statements ] LineTerminator LabelName ::= Identifier | IntLiteral Statements ::= [ Statement ] | Statements [ Statement ]

Instrucciones de declaracin de variables locales


LocalDeclarationStatement ::= LocalModifier LocalDeclarator StatementTerminator LocalModifier ::= Dim | Const LocalDeclarator ::= LocalIdentifiers [ As TypeName ] Identifier [ ArrayNameModifier ] [ As [ New ] TypeName [ ( [ ArgumentList ] ) ] ] [ = VariableInitializer ] LocalIdentifiers ::= Identifier [ ArrayNameModifier ] | LocalIdentifiers , Identifier [ ArrayNameModifier ] LocalVariableName ::= Identifier

Instruccin With
WithStatement ::= With Expression StatementTerminator

[ Block ] End With StatementTerminator

Instruccin SyncLock
SyncLockStatement ::= SyncLock Expression StatementTerminator [ Block ] End SyncLock StatementTerminator

Instrucciones de eventos
EventStatement ::= RaiseEventStatement | AddHandlerStatement | RemoveHandlerStatement

Instruccin RaiseEvent
RaiseEventStatement ::= RaiseEvent EventMemberName [ ( [ ArgumentList ] ) ] StatementTerminator

Instrucciones AddHandler y RemoveHandler


AddHandlerStatement ::= AddHandler HandlerArguments StatementTerminator RemoveHandlerStatement ::= RemoveHandler HandlerArguments StatementTerminator HandlerArguments ::= EventExpression , ArgumentExpression

Instrucciones de asignacin
AssignmentStatement ::= SimpleAssignmentStatement | DelegateAssignmentStatement | CompoundAssignmentStatement | MidAssignmentStatement

Instrucciones de asignaciones simples


RegularAssignmentStatement ::= VariableExpression = Expression StatementTerminator VariableExpression ::= Expression

Instrucciones de asignaciones de delegado


DelegateAssignmentStatement ::= VariableExpression = AddressOf InvocationTargetExpression StatementTerminator

Instrucciones de asignaciones compuestas


CompoundAssignmentStatement ::= VariableExpression CompoundBinaryOperator = Expression StatementTerminator CompoundBinaryOperator ::= ^ | * | / | \ | + | - | &

Instruccin de asignacin Mid


MidAssignmentStatement ::= Mid [ $ ] ( VariableExpression , Expression [ , Expression ] ) = Expression StatementTerminator

Instruccin de invocacin
InvocationStatement ::= [ Call ] InvocationExpression StatementTerminator

Instrucciones condicionales
ConditionalStatement ::= IfStatement | SelectStatement

If...Then...Else (Instrucciones)
IfStatement ::= BlockIfStatement | LineIfThenStatement BlockIfStatement ::= If BooleanExpression [ Then ] StatementTerminator [ Block ] [ ElseIfStatement+ ] [ ElseStatement ] End If StatementTerminator ElseIfStatement ::= ElseIf BooleanExpression [ Then ] StatementTerminator [ Block ] ElseStatement ::=

Else StatementTerminator [ Block ] LineIfThenStatement ::= If BooleanExpression Then [Statements ] [ Else Statements ] StatementTerminator BooleanExpression ::= Expression

Instrucciones Select...Case
SelectStatement ::= Select [ Case ] Expression StatementTerminator [ CaseStatement+ ] [ CaseElseStatement ] End Select StatementTerminator CaseStatement ::= Case CaseClauses StatementTerminator [ Block ] CaseClauses ::= CaseClause | CaseClauses , CaseClause CaseClause ::= [ Is ] ComparisonOperator Expression | Expression [ To Expression ] ComparisonOperator ::= = | < > | < | > | = > | = < CaseElseStatement ::= Case Else StatementTerminator [ Block ]

Instrucciones de bucle
LoopStatement ::= WhileStatement | DoLoopStatement | ForStatement | ForEachStatement

Instrucciones While...End While y Do...Loop


WhileStatement ::= While BooleanExpression StatementTerminator [ Block ] End While StatementTerminator DoLoopStatement ::= Do [ WhileOrUntil BooleanExpression ] StatementTerminator [ Block ] Loop [ WhileOrUntil BooleanExpression ] StatementTerminator WhileOrUntil ::= While | Until

For...Next (Instrucciones)
ForStatement ::= For LoopControlVariable = Expression To Expression [ Step Expression ] StatementTerminator [ Block ] Next [ NextExpressionList ] StatementTerminator LoopControlVariable ::= Identifier As TypeName | Expression NextExpressionList ::= VariableExpression | NextExpressionList , VariableExpression

For Each...Next (Instrucciones)


ForEachStatement ::= For Each LoopControlVariable In Expression StatementTerminator [ Block ]

Next [ VariableExpression ] StatementTerminator

Instrucciones de control de excepciones


ExceptionHandlingStatement ::= StructuredExceptionStatement | UnstructuredExceptionStatement

Instrucciones de control estructurado de excepciones


StructuredExceptionStatement ::= ThrowStatement | TryStatement ThrowStatement ::= Throw [ Expression ] StatementTerminator TryStatement ::= Try StatementTerminator [ Block ] [ CatchStatement+ ] [ FinallyStatement ] End Try StatementTerminator

Bloques Finally
FinallyStatement ::= Finally StatementTerminator [ Block ]

Bloques Catch
CatchStatement ::= Catch [ Identifier As TypeName ] [ When BooleanExpression ] StatementTerminator [ Block ]

Instrucciones de control no estructurado de excepciones


UnstructuredExceptionStatement ::= ErrorStatement | OnErrorStatement | ResumeStatement

Instruccin Error
ErrorStatement ::= Error Expression StatementTerminator

Instruccin On Error
OnErrorStatement ::= On Error ErrorClause StatementTerminator ErrorClause ::= Resume Next | GoTo -1 | GoTo 0 | GotoStatement

Instruccin Resume
ResumeStatement ::= Resume [ ResumeClause ] StatementTerminator ResumeClause ::= Next | LabelName

Instrucciones de flujo de control


ControlFlowStatement ::= GotoStatement | ExitStatement | StopStatement | EndStatement | ReturnStatement GotoStatement ::= GoTo LabelName StatementTerminator ExitStatement ::= Exit ExitKind StatementTerminator ExitKind ::= Do | For | While | Select | Sub | Function | Property | Pruebe StopStatement ::= Stop StatementTerminator EndStatement ::= End StatementTerminator ReturnStatement ::= Return [ Expression ]

Instrucciones de control de matrices


ArrayHandlingStatement ::= RedimStatement | EraseStatement

Instruccin ReDim
RedimStatement ::= ReDim [ Preserve ] RedimClauses+ StatementTerminator RedimClauses ::= RedimClauses | RedimClause , RedimClauses RedimClause ::= VariableExpression ArrayInitializationModifier

Instruccin Erase
EraseStatement ::= Erase VariableExpressions StatementTerminator VariableExpressions ::= VariableExpression | VariableExpressions , VariableExpression

Expresiones
Expression ::= SimpleExpression | InvocationExpression | MemberAccessExpression | IndexExpression | NewExpression | CastExpression | TypeOfExpression | OperatorExpression

Expresiones constantes
ConstantExpression ::= Expression

Expresiones variables
VariableExpression ::= Expression

Expresiones de eventos
EventExpression ::= Expression . IdentifierOrKeyword | [ MeExpression . ] IdentifierOrKeyword | EventMemberName

Expresiones simples
SimpleExpression ::= LiteralExpression | ParenthesizedExpression | MeExpression | MetaTypeExpression | LocalVariableExpression | TypeOfIsOperatorExpression | IsOperatorExpression

Expresiones literales
LiteralExpression ::= Literal

Expresiones entre parntesis


ParenthesizedExpression ::= ( Expression )

Expresin Me
MeExpression ::= Me

Expresiones GetType
MetaTypeExpression ::= GetType ( TypeName )

Expresiones de variable local


LocalVariableExpression ::= LocalVariableName

Expresiones TypeOf...Is

TypeOfIsOperatorExpression ::= TypeOf Expression Is TypeName

Expresiones Is
IsOperatorExpression ::= Expression Is Expression

Expresiones de invocacin
InvocationExpression ::= InvocationTargetExpression [ ( [ ArgumentList ] ) ] InvocationTargetExpression ::= DelegateExpression | [ [ Expression ] . ] IdentifierOrKeyword | MyClass . IdentifierOrKeyword | MyBase . IdentifierOrKeyword | MethodMemberName DelegateExpression ::= Expression

Listas de argumentos
ArgumentList ::= PositionalArgumentList , NamedArgumentList | PositionalArgumentList | NamedArgumentList PositionalArgumentList ::= ArgumentExpression | PositionalArgumentList , [ ArgumentExpression ] NamedArgumentList ::= Identifier : = ArgumentExpression | NamedArgumentList , Identifier : = ArgumentExpression ArgumentExpression ::= Expression | DelegateArgumentExpression

Expresiones de argumentos de delegado


DelegateArgumentExpression ::= AddressOf InvocationTargetExpression

Expresiones de acceso a miembros


MemberAccessExpression ::= [ [ Expression ] . ] IdentifierOrKeyword | VariableMemberName | PropertyMemberName | ConstantMemberName | EnumMemberName | DictionaryAccessExpression

Acceso a miembros de tipo diccionario


DictionaryAccessExpression ::= [ Expression ] ! IdentifierOrKeyword

Expresiones de ndice
IndexExpression ::= Expression ( ArgumentList )

Expresiones New
NewExpression ::= ObjectCreationExpression | ArrayCreationExpression | DelegateCreationExpression

Expresiones de creacin de objetos


ObjectCreationExpression ::= New TypeName [ ( [ ArgumentList ] ) ]

Expresiones de creacin de matrices


ArrayCreationExpression ::= New TypeName ( ArgumentList ) ArrayElementInitializer | New ArrayTypeName ArrayElementInitializer

Expresiones de creacin de delegados


DelegateCreationExpression ::= New TypeName ( InvocationTargetExpression )

Expresiones de conversin
CastExpression ::= CType ( Expression , TypeName ) |

CastTarget ( Expression ) CastTarget ::= CBool | CByte | CChar | CDate | CDec | CDbl | CInt | CLng | CObj | CShort | CSng | CStr

Operadores
OperatorExpression ::= UnaryOperatorExpression | BinaryOperatorExpression BinaryOperatorExpression ::= ArithmeticOperatorExpression | RelationalOperatorExpression | LikeOperatorExpression | ConcatenationOperatorExpression | ShortCircuitLogicalOperatorExpression | LogicalOperatorExpression | ShiftOperatorExpression

Operadores unarios
UnaryOperatorExpression ::= UnaryPlusExpression | UnaryMinusExpression | UnaryLogicalNotExpression

Operador unario ms
UnaryPlusExpression ::= + Expression

Operador unario Menos


UnaryMinusExpression ::= - Expression

Operador de negacin lgica


UnaryLogicalNotExpression ::= Not Expression

Operadores aritmticos
ArithmeticOperatorExpression ::= AdditionOperatorExpression | SubtractionOperatorExpression | MultiplicationOperatorExpression | DivisionOperatorExpression | ModuloOperatorExpression | ExponentOperatorExpression

Operador de suma
AdditionOperatorExpression ::= Expression + Expression

Operador de resta
SubtractionOperatorExpression ::= Expression - Expression

Operador de multiplicacin
MultiplicationOperatorExpression ::= Expression * Expression

Operador de divisin
DivisionOperatorExpression ::= RegularDivisionOperatorExpression | IntegerDivisionOperatorExpression RegularDivisionOperatorExpression ::= Expression / Expression IntegerDivisionOperatorExpression ::= Expression \ Expression

Operador Mod
ModOperatorExpression ::= Expression Mod Expression

Operador de exponenciacin
ExponentOperatorExpression ::= Expression ^ Expression

Operadores relacionales
RelationalOperatorExpression ::= Expression = Expression | Expression < > Expression | Expression < Expression |

Expression > Expression | Expression < = Expression | Expression > = Expression

Operador Like
LikeOperatorExpression ::= Expression Like Expression

Operador de concatenacin
ConcatenationOperatorExpression ::= Expression & Expression

Operadores lgicos
LogicalOperatorExpression ::= Expression And Expression | Expression Or Expression | Expression Xor Expression | Expression AndAlso Expression | Expression OrElse Expression

Operadores de desplazamiento
ShiftOperatorExpression ::= Expression << Expression | Expression >> Expression